Following/Seeking a Moving Position with Velocity & Sin/Cos

graph theoryphysicstrigonometryvectors

So basically I am writing a 2D game and ran into a mathematical issue implementing a really simple "seeking" projectile, where it chases the player (who can move).

The projectile acts as follows every update (120 times a second):

  • Set its velocity based on its speed and angle relative to the target (player).
    • The velocity is calculated by x = speed * cos(angle) and y = speed * sin(angle), where angle between projectile and target is calculated with atan2(targetX – projectileX, targetY – projectileY) * 180 / PI.
  • Add the velocity to the projectile's current position (velocityX + posX, velocityY + posY).

It works as intended ONLY when the player is sitting still. When the player starts moving around, the projectile is basically sitting in place when translating horizontally/vertically relative to it. The projectile looks like it is "bouncing" up or staying "in place" when moving left/right rapidly, or if you move around it in a circle it stays in place – despite its magnitude being the same, expected projectile speed every instant.

Am I calculating something wrong, or am I doing something wrong logically here?

Best Answer

It doesn't specify what language you are using, but atan2 almost universally takes the $y$ coordinate first and the $x$ coordinate second, and then why are you converting that out of radians and into degrees? I hope to goodness you are not using the angle in degrees in sin and cos. I don't know of any computer language which uses degrees for those functions.

Am I calculating something wrong, or am I doing something wrong logically here?

You must be mustn't you? If you weren't calculating something wrong or doing something wrong logically you wouldn't have a problem.

Related Question