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

2024/1/12

An error with get key

Garrison Garrison

2024/1/12

#
I have a program where a knight and lance switch between three lanes, it uses a get key to move either up or down, however only one of the two ever moves at a time.
String key = Greenfoot.getKey();
        System.out.println(key);
        if("w".equals(key) ){
            System.out.println("here");
            if(y > 100){
                y = y - 100;
                charge(y,di);
            }
        }
        if("s".equals(key)){
             System.out.println("here");
            if(y < 300){
                y = y + 100;
                charge(y,di);
            }
            
            
        }
        if(Greenfoot.isKeyDown("space")){
            System.out.println("pere");
        }
        else{
            charge(y,di);
        }
danpost danpost

2024/1/13

#
Garrison wrote...
I have a program where a knight and lance switch between three lanes, it uses a get key to move either up or down, however only one of the two ever moves at a time.
That is because the getKey method can only be used once per act step. That is, when a key is "grabbed" from the keyboard buffer, it is removed from the buffer. So, calling it a second time will not return that same keystroke again. One way of dealing with this is to have the world use getKey to get it and save it in a variable where the actors can gain access to it.
// variable in world class
public static String key;

// during act
key = Greenfoot.getKey();
In actor classes (example world type: MyWorld)
// during act
if ("w".equals(MyWorld.key)) {
    // etc.
if ("s".equals(MyWorld.key)) {
    // etc.
Garrison Garrison

2024/1/13

#
Thank you very much!
You need to login to post a reply.