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

547 Views Asked by At

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?

2

There are 2 best solutions below

3
On 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.

1
On

You might have a better time if you avoid the trig functions altogether.

Let $\Delta x = \mathbf{targetX} - \mathbf{projectileX}.$
Let $\Delta y = \mathbf{targetY} - \mathbf{projectileY}.$
Let $\Delta s = \sqrt{(\Delta x)^2 + (\Delta y)^2}.$

Then set $$\mathbf{velocityX} = \mathbf{speed} \times \frac{\Delta x}{\Delta s}$$ and set $$\mathbf{velocityY} = \mathbf{speed} \times \frac{\Delta y}{\Delta s}.$$

The trick here is that $\operatorname{atan2}(\Delta y, \Delta x)$ returns an angle $\theta$ in radians such that $$ \cos(\theta) = \frac{\Delta x}{\sqrt{(\Delta x)^2 + (\Delta y)^2}} \tag1 $$ and $$ \sin(\theta) = \frac{\Delta y}{\sqrt{(\Delta x)^2 + (\Delta y)^2}}, \tag2$$

so essentially all you are doing with the three trig functions (in the corrected version of the code) is to go from $\Delta x$ and $\Delta y$ to the right-hand sides of Equations $(1)$ and $(2)$. And you can do that directly just by computing the square root and dividing, skipping the steps involving $\theta$.