# How to get enemy to follow character using angles? (atan2)

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.

• 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 1 '13 at 2: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 1 '13 at 12:44

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);
}

• 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. – Raceimaztion Jan 1 '13 at 5:13
• Thanks! This worked really well and the enemy moves really smoothly. – dizzydj7 Jan 3 '13 at 21:32
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.

• 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 1 '13 at 2:59