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

2015/8/26

Going Up and Down

Camyh15 Camyh15

2015/8/26

#
Hello, I'm trying to make a slider go up and down with the arrow keys and I have this code so far:
1
2
3
4
5
6
setRotation(90);
if (Greenfoot.isKeyDown("up"))
move(-7);
if(Greenfoot.isKeyDown("down"))
move(7);
setRotation(0);
Thank you!
danpost danpost

2015/8/26

#
More appropriately, it should be written in one of the following two ways:
1
2
3
4
5
6
7
8
9
10
setRotation(90);
if (Greenfoot.isKeyDown("up"))
{
    move(-7);
}
if (Greenfoot.isKeyDown("down"))
{
    move(7);
}
setRotation(0);
or
1
2
3
4
setRotation(90);
if (Greenfoot.isKeyDown("up")) move(-7);
if (Greenfoot.isKeyDown("down")) move(7);
setRotation(0);
Even the following would be a fair way (at least the 'move' statements are easily seen as not being at the same execution level as the rotation setting lines:
1
2
3
4
5
6
setRotation(90);
if (Greenfoot.isKeyDown("up"))
    move(-7);
if (Greenfoot.isKeyDown("down"))
    move(7);
setRotation(0);
The 'setLocation' method might be more appropriate here to avoid rotating and resetting of the rotation:
1
2
if (Greenfoot.isKeyDown("up")) setLocation(getX(), getY()-7);
if (Greenfoot.isKeyDown("down")) setLocation(getX(), getY()+7);
or (to avoid both 'if' blocks being executed when both the 'up' and 'down' keys are pressed simultaneously):
1
2
3
4
int dy = 0;
if (Greenfoot.isKeyDown("up")) dy--;
if (Greenfoot.isKeyDown("down")) dy++;
setLocation(getX(), getY()+7*dy);
Usually however, sliders have limits as to how far in either direction that it is allowed to go. With this last way of coding, checking the limits can be done with code inserted between lines 3 and 4 (check the value of 'getY()+7*dy' and set dy to zero if that value is out of wanted bounds.)
Camyh15 Camyh15

2015/8/27

#
Camyh15 wrote...
Thank you sooooooooooooooo much!!!!!!!!!!
Francis1004 Francis1004

2015/8/27

#
but how do you make it move up and down without pressing any key?
danpost danpost

2015/8/27

#
In my last code-set posted (the final 4-liner), move line 1 outside the method and set its value to 1 or -1. Check he the same value for changing direction (the inserted code between lines 3 and 4), but you now have dual conditions for changing each way. If currently moving toward a specific edge and the new coordinate reaches that edge, then change directions. You will need a set of dual conditions for each possible edge that the object can reach.
You need to login to post a reply.