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

2013/5/8

moving

mellotelli45 mellotelli45

2013/5/8

#
how do you move your object up and down and side to side but without letting it go diagonally
bourne bourne

2013/5/8

#
Something like this (only let it move for one direction once per act cycle):
if (Greenfoot.isKeyDown("up"))
    moveUp();
else if (Greenfoot.isKeyDown("down"))
    moveDown();
else if (Greenfoot.isKeyDown("left"))
    moveLeft();
else if (Greenfoot.isKeyDown("right"))
    moveRight();
mellotelli45 mellotelli45

2013/5/8

#
how do you do the background
danpost danpost

2013/5/8

#
The code you gave above should only move the actor in one of the four cardinal directions. However, it is biased toward the vertical direction and biased toward the negative direction (meaning if you are holding down two arrow keys, your actor will go in the direction of a vertical movement key first; and then, your actor will go 'up' or 'left' before going 'down' or 'right' along the determined vertical or horizontal). One way to avoid this biased movement is to collect the sum of the vertical and horizontal directional keys first; then, skip any diagonal movements. What remains is movement along the horizontal or vertical or no movement at all.
int dx = 0; // local field to hold movement along the x-axis
int dy = 0; // local field to hold movement along the y-axis
if (Greenfoot.isKeyDown("up")) dy--; // adjust y-axis movement upward
if (Greenfoot.isKeyDown("down")) dy++; // adjust y-axis movement downward
if (Greenfoot.isKeyDown("left")) dx--; // adjust x-axis movement toward left
if (Greenfoot.isKeyDown("right")) dx++; // adjust x-axis movement toward right
if (dx * dy == 0) setLocation(geX()+dx, getY()+dy); // if not diagonal movement, move (or stay, if no movement at all)
'dx' and 'dy' can be multiplied by a speed factor in the 'setLocation' statement. An added bonus to this code is that you do not need separate methods to move in each direction.
NU22 NU22

2016/5/1

#
I used this code and it does not work, gives me errors such as illegal start of type and missing semicolons. Has there been an update to Greenfoot that makes this no longer work?
danpost danpost

2016/5/1

#
NU22 wrote...
I used this code and it does not work, gives me errors such as illegal start of type and missing semicolons. Has there been an update to Greenfoot that makes this no longer work?
The only issue I see with the code is that in the last line 'geX()' should be 'getX()'. Other than that, it should work. Maybe you should post the code of the class you are trying to use it in. Seems to me that your errors are more general in nature.
You need to login to post a reply.