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

2018/9/5

Back and forth movement

1
2
DavidTshitenda DavidTshitenda

2018/9/7

#
Danpost do you mind explaining that bit of code?
Super_Hippo Super_Hippo

2018/9/7

#
No, you don't. You only get this error if your variable isn't static and you have to add a 'static' there to make it work. (Or use danpost's code.) Looks like I am still confused if the x-value should be changed (moving along the y-axis) or vice versa...
danpost danpost

2018/9/9

#
Explaining:
private int dirY = 1; // for the current direction ( 1 : up ;  -1 : down)
private int distY = 0; // for steps taken in current direction

public void act()
{
    setLocation(getX(), getY()+dirY); // move in direction
    distY = (distY+1)%5; // increment step count (with wrap: zeroes when incremented to 5)
    if (distY == 0) dirY = -dirY; // if 5 steps have been taken, reverse direction
}
You need to login to post a reply.
1
2