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

2016/6/12

Facing in the direction of movement

JamesHughes244 JamesHughes244

2016/6/12

#
Below is my current code for movement. I would like the actor to face in the direction of movement. For example if the up arrow is pressed, the actor will move north and the image for that actor will turn to face north. Here is my current code:
1
2
3
4
5
6
7
public void moveAndTurn()
   {
       if (Greenfoot.isKeyDown("up"))setLocation(getX(),getY()-1);
       if (Greenfoot.isKeyDown("down"))setLocation(getX(), getY()+1);
       if (Greenfoot.isKeyDown("left"))setLocation(getX()-1, getY());
       if (Greenfoot.isKeyDown("right"))setLocation(getX()+1, getY());
   }
SPower SPower

2016/6/12

#
You can use the setRotation method, which will also automatically rotate the image accordingly. The argument of setRotation is in degrees, starting with pointing to the right, and rotating 'up' first (i.e. 90 degrees is facing up, then 180 left, etc.). With that, you can use the move method to move the object forward according to its direction.
danpost danpost

2016/6/12

#
SPower wrote...
You can use the setRotation method, which will also automatically rotate the image accordingly. The argument of setRotation is in degrees, starting with pointing to the right, and rotating 'up' first (i.e. 90 degrees is facing up, then 180 left, etc.). With that, you can use the move method to move the object forward according to its direction.
The degrees actually go up in a clockwise fashion -- meaning "down" is 90 degrees, "left" is 180 and "up" is 270.
SPower SPower

2016/6/12

#
Whoopsie, got confused (again). Thanks for the correction.
JamesHughes244 JamesHughes244

2016/6/12

#
Thats great, thanks SPower and danpost
You need to login to post a reply.