2
\$\begingroup\$

I have an enemy and a character to control. I want to get the enemy to follow the character in a straight line. I already found the angle in which the enemy needs to travel.

double angle = Math.atan2(y, x) * 180 / Math.PI;

Now, let's say it return 73.0. What do I do with that number? And what if it's a negative angle.

BTW, I'm using dx(dynamic x) and dy(dynamic y) to control movement.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ you don't really need atan2 though. Treat the difference in x and y value as vector components. Normalize them and multiply it with a "speed". \$\endgroup\$
    – Sidar
    Jan 1, 2013 at 2:53
  • \$\begingroup\$ Though you do not need trigonometric functions here, the arctan yields 'the angle'. There are only a few reasons for converting to degrees; your wording suggests they don't apply. Useful calculations are generally done in radians. \$\endgroup\$ Jan 1, 2013 at 12:44

2 Answers 2

6
\$\begingroup\$

You do not need to know the angle, because the difference in X and Y already gives you the desired orientation of the enemy. The only thing that remains to be done is normalise that direction vector (if possible -- otherwise it means the player and the enemy are exactly at the same position), and multiply it by the enemy’s speed:

dx = player_x - enemy_x;
dy = player_y - enemy_y;
float norm = Math.sqrt(dx * dx + dy * dy);
if (norm)
{
    dx *= (enemy.speed / norm);
    dy *= (enemy.speed / norm);
}
\$\endgroup\$
2
  • \$\begingroup\$ This has the major advantage of not needing to do any sines and cosines, which can take longer to perform than a relatively simple square-root. \$\endgroup\$ Jan 1, 2013 at 5:13
  • \$\begingroup\$ Thanks! This worked really well and the enemy moves really smoothly. \$\endgroup\$
    – dizzydj7
    Jan 3, 2013 at 21:32
4
\$\begingroup\$
double angle = Math.atan2(y,x);  // Note: keeping angle in radians for cos & sin.
dx = enemy.speed * Math.cos( angle );
dy = enemy.speed * Math.sin( angle );

This will work fine with negative angles.

See also: What are atan and atan2 used for in games?

\$\endgroup\$
1
  • \$\begingroup\$ Thank you. I tried this, and it works fine while the character is still. But while the character is moving, the enemy just shakes. Any idea how to fix this? \$\endgroup\$
    – dizzydj7
    Jan 1, 2013 at 2:59

You must log in to answer this question.

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