Today I am trying to make it so if I hit the enemy then the enemy will be knocked backwards in the direction the sprite is facing. I am rotating the sprite around 360 degrees using a joystick on the screen and wanted to know the best practice or ways to accomplish this. I have come up with a few ideas but none of them make use of the sprites angle he is facing just a check to see if I hit the bottom then move him upward and so forth. I am just stumped on how to apply the sprites angle to the enemies x and y coordinate and move him accordingly. Has anyone tried this and have suggestions or things to look for?


1 Answer 1


You'll need to turn the angle of rotation into a 2d vector which represents the direction the sprite is facing. You can then add or subtract this 2d vector onto the sprites position to move it forward or backwards in the direction it's facing.

You can generate the vector with something as simple as using cos() and sin() for the X and Y components of this vector. (you'll need to ensure you don't mix degrees and radians when passing into these functions - plus ensure that when the angle is Zero that your sprite is facing directly right, although you could fix this by adding a constant onto the angle passed into cos/sin to adjust for any rotation that exists in the sprite).

  • \$\begingroup\$ Hey Roger, thanks for your answer, Ialmost go this to work fo rme by using this code <pre>setenemyPositionY(getenemyPositionY() + Math.sin(getRotation() * (Math.PI / 180))); setenemyPositionX(getenemyPositionX() + Math.cos(getRotation() * (Math.PI / 180))); </pre> Is this what you were talking about? This seems to work however alwasy launches the enemy to my right. Ill keep working on it though. Thanks for your help. \$\endgroup\$
    – pengume
    Mar 14, 2011 at 8:10
  • \$\begingroup\$ Yeah, something like that. If it's always sending the sprite off in a direction that's say 90 degrees out then chances are the sprite doesn't face in the same direction that lines up with Zero degrees. You can work around this by adding a constant to the value returned by getRotation() to shift the rotation angle around to compensate for this discrepancy. \$\endgroup\$ Mar 14, 2011 at 10:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .