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

2015/3/4

Key controll

EduandErnst EduandErnst

2015/3/4

#
Hi, When I have a code like that.
if (Greenfoot.isKeyDown("right"){
moveright();
}
else if (Greenfoot.isKeyDown("up"){
jumpright();
}
else if (Greenfoot.isKeyDown("right") && Greenfoot.isKeyDown("up") ) {
moveright();
jumpright();
}
is it actually possible to check the keys like that? Or how would I Need to write it, when I two assignments for one key? Any suggestions?
danpost danpost

2015/3/4

#
EduandErnst wrote...
< Code Omitted > is it actually possible to check the keys like that?
Similar to that maybe; but, not like that. For one thing, the 'if' condition on line 7 will never even be checked. If either part of the condition was true then a previous if would be true and its block would be executed (because using 'else'denies a second block to be executed). If you checked the conditions on line 7 first, then if not both keys were down, the conditions of the individual keys would still be checked.
davmac davmac

2015/3/4

#
One alternative (though not necessarily the simplest) is to move the check for both conditions to the top:
if (Greenfoot.isKeyDown("right") && Greenfoot.isKeyDown("up") ) {
    moveright();
    jumpright();
}
else if (Greenfoot.isKeyDown("right"){
    moveright();
}
else if (Greenfoot.isKeyDown("up"){
    jumpright();
}
Better would be to split the left/right and jump handling, essentially so that "left"/"right" both move and change the direction the player is facing, and "up" jumps in the direction they are facing.
You need to login to post a reply.