Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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
up vote 6 down vote accepted

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);
share|improve this answer
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.

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

share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.