How to automatically rotate a sprite to make it face a certain point!
-
I noticed this question comes up a lot, and it has been answered in a few different places, but I thought I would make a separate topic to make it easy to find.
A common scenario is that you have a sprite and you want to rotate it so that it faces another sprite. It could be that incoming enemies are flying towards you, and you want their ships to move with the front first. Or maybe you want your player sprite to face the direction where your target reticle is?
This is how you do it (in three easy steps) if you have a playerSpr sprite that you want to face a targetSpr sprite:
- Calculate the vector that describes the difference between the two sprites.
diff = getSpriteLocation(playerSpr) - getSpriteLocation(targetSpr)
- Calculate the angle in degrees using atan2. This is a mathematical formula that takes as input the y difference and the x difference and returns the angle.
angle = atan2(diff.y, diff.x)
- Now that we have the angle, we can rotate the player sprite. Depending on the original orientation of the sprite you may need to add an offset (generally + or - 90 degrees).
setSpriteRotation(playerSpr, angle - 90)
It is all really simple. As a bonus, this is how you can get the distance between the sprites:
dist = sqrt(diff.y * diff.y + diff.x * diff.x)
Here is a small working example that you can download and try it out for yourself:
ID: NXK76GP92C
-
Awesome indeed. I'm sure I can find a use for this ;)
Thanks. -
Oh yeah, someone gave a TED talk on this a while back :)