Hi guys, I’m trying to solve this particular challenge, here’s the scenario:
I have 2 sprites:
one sprite is a matter enabled sprite, a boat.
the second sprite is just a phaser sprite with no physics, a cannon.
When the game starts, the cannon is positioned on top of the boat, at a fixed position relative to the boat’s position, using the boat’s X and Y values and an offset.
When the boat goes forward and ONLY forward, the cannon stays in position nicely. What I need to solve is when the ship rotates, as shown in the GIF at the end of this post. When the ship rotates the cannon should stay always in it’s place above the boat’s deck. I think I would need to calculate where that new (x,y) is and adjust accordingly maybe, but I am not sure on how to do that. The boat’s movement is like this:
When UP is pressed, a THRUST is applied to the boat.
When LEFT or RIGHT are pressed, a value is assigned to the Angular Velocity of the boat, making it
rotate on his central axis.
Any suggestions will be gladly welcome! I am still a begginer in Phaser, and game developing in general. The reason behind the cannon being another sprite, is because I have different keys to rotate it clockwise or counter clockwise for aiming.
You are correct that you would need to adjust the cannon’s X/Y position and rotation every frame so that it is attached to the boat. With a setup as simple as this, you could do it manually, but you can also use Containers for it. They’ll likely make it a little simpler, but I’ve never used them, so I can’t give you good advice about them.
If you decide to try to do this yourself, what you’re looking for is a simple formula for rotating a point a given distance away from another point - you know where the cannon should be when the ship is at a 0° angle, so you can rotate that known point around the ship’s center point by the ship’s rotation - you can do this with Phaser.Math.RotateAround or use the general formula for it (that post is the first result on Google, it looks correct). This would attach the cannon to the ship, but it wouldn’t visually rotate - what I’d do in this case is set its origin to the center of its left side (cannon.setOrigin(0, 0.5), where cannon is your Game Object), then set its rotation to be equal to the ship’s rotation (plus or minus whichever angle it’s pointed at). You can do all of this in your update method.
Telinc1 thank you! Your reply was very insightful and useful.
I ended up using the RotateAroundDistance function of Phaser.Math and manually adjusting the cannon with the resulting coordinates.