2

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.

dizzydj7
  • 105
  • 2
  • 11
  • 1
    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". – Sidar Jan 01 '13 at 02:53
  • 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. – Marcks Thomas Jan 01 '13 at 12:44

2 Answers2

6

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);
}
sam hocevar
  • 23,811
  • 2
  • 63
  • 95
4
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?

AbePralle
  • 455
  • 5
  • 4
  • 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? – dizzydj7 Jan 01 '13 at 02:59