0
\$\begingroup\$

In a libgdx project of mine, I have two units on a 2d field who want to fire at each other. They both know the x and y distance to each other by subtracting their enemies position from their own:

Vector2 path = pos.cpy().sub(target.getPos());

What's the simplest way of turning this Vector2 into a vector that'll allow the units to fire at each other, with the projectile being sent off with Projectile.maxSpeed?

I was thinking of normalizing path and multiplying both x and y with the desired bullet speed, but I fear I may be overthinking this and that applying trigonometry would be simpler.

\$\endgroup\$
2
\$\begingroup\$

Your intuition is correct, the easiest way to do it would be to normalize your vector, and then rescale it using the Projectile.maxSpeed. If you need the angle for some reason, you can get the direction to the target by using the atan2, which can be used to convert an x and y difference into a rotation. Here's some C pseudo-code to show you:

float x_diff = target.x - me.x;
float y_diff = target.y - me.y;
float direction_to_target = atan2(y_diff, x_diff);
float direction_to_target_degrees = direction_to_target * 180 / PI;
\$\endgroup\$
1
  • \$\begingroup\$ I do not need the angle, which is why I was hesitant when it comes to involving trig in this. Tested with normalizing via Vector2.nor() and then multiplying it with the base speed. it worked like a charm. Cheers! \$\endgroup\$
    – Jarmund
    Jul 17 '16 at 22:50

You must log in to answer this question.

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