Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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
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 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
add comment

2 Answers

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
add comment
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
add comment

Your Answer

 
discard

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.