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

2017/12/21

help!

agray11202 agray11202

2017/12/21

#
how to turn an object 90 degrees to the direction of the key you pressed (up, down, left, right)
Super_Hippo Super_Hippo

2017/12/21

#
Do you mean you want to turn to the right side when the right arrow key is pressed? For example if the current rotation is 180° (facing left), what should the rotation be when you press the right arrow key? 0° (facing right) or turning right 90° from left which then would be 270° (or 90°?). In the future, please use a real description for the discussion and not 'help!'.
danpost danpost

2017/12/22

#
First, determine which direction the actor should turn toward, then turn toward that direction. There are two possible horizontal and two possible vertical directions and only one of the two, horizontal or vertical, can be allowed at one time.
int dx = 0; // for horizontal direction
if (Greenfoot.isKeyDown("left")) dx--;
if (Greenfoot.isKeyDown("right")) dx++;
int dy = 0; // for vertical direction
if (Greenfoot.isKeyDown("up")) dy--;
if (Greenfoot.isKeyDown("down")) dy++;
if (dx*dy == 0 && dx+dy != 0) // if one is zero and the other is not
{
    int rotation = 0;
    if (dx != 0) rotation = 90*(1-dx); // horizontal
    else rotation = 90*(2-dy); // vertical
    setRotation(rotation); // turn
}
agray11202 agray11202

2017/12/22

#
Thank you so much danpost!!! Just wondering, does this code go in my act method or should I create another method to put it in?
Super_Hippo Super_Hippo

2017/12/22

#
Either in the act method or a method which you call from the act method. There is nothing wrong about just putting it into the act method.
You need to login to post a reply.