You need to calculate the direction of the actor
Like in my Asteroid game I want the Flying Saucer to attack the world has a variable which points to the rocket
Step 1 you need to get the x and y coordinates of the target (eg Rocket)
Step 2: use simple trig to calcuate the angle ( note that at 90 and 270 degrees , tangent is undefined so you need to ]
be a little smart about using the Math function
Here is my code for this:
protected int getDirection (int xTarget,int yTarget){
double dx = xTarget- getX();
double dy = yTarget- getY();
if (dx == 0 ) // vertical and can't use arctan to calculate angle
if (yTarget >= getY())
return 90;
else return -90;
// calculate angle
double angle = Math.atan2(dy,dx);
double degrees = angle*360 /2/Math.PI;
return (int)degrees;
}
----
Step3: use set Rotation like so : setRotation ( degrees);
Cheers Takashi
@ttamasu you don't need the extra logic, atan2 takes care of those corner cases. There's also a Math.toDegrees function you can use.
@tylers if you're using Greenfoot 2.2.0 beta, there is a new turnTowards method in Actor that will do exactly what you want. Otherwise, follow ttamasu's suggestion.