This site requires JavaScript, please enable it in your browser!
Greenfoot back
tylers
tylers wrote ...

2012/4/6

turn towards

tylers tylers

2012/4/6

#
how do you get an actor to turn towards another actor?
ttamasu ttamasu

2012/4/6

#
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
nccb nccb

2012/4/6

#
@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.
tylers tylers

2012/4/6

#
how do i get it to turn towards the closes object to the actor. eg; fish going to fish food. @nccb i am running greenfoot 2.2.0
davmac davmac

2012/4/6

#
You can't be running Greenfoot 2.2.0, it hasn't been released. You mean the beta?
tylers tylers

2012/4/7

#
yes forgot to put that.
You need to login to post a reply.