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

2016/4/7

Strange keyboard behavior

TinyTertle TinyTertle

2016/4/7

#
I have the following class implemented in order to better control keyboard input...
import greenfoot.*;
public class KeyboardInput  
{
    String currentKey = null;
    String previousKey = null;
    
    public void update()
    {
        previousKey = currentKey;
        currentKey = Greenfoot.getKey();
    }
    public boolean keyHit(String key)
    {
        return key.equals(currentKey) && !key.equals(previousKey);
    }
}
Where update() is called in the World's act() method. The purpose of keyHit() is to ensure that key input is only registered once per press. For example. If I call
if(keyboardInputObject.keyHit("enter")) System.out.println("enter hit");
in my game loop the statement will be printed if I press enter and will not be reprinted until I release the key and press it again. Unfortunately the code only partially works. If I press and hold "enter", the statement is printed and after a brief delay input is delivered at the update rate. I can't figure out what's going on. Can anyone help?
danpost danpost

2016/4/8

#
I appears you need to track what keys are being held down. Something like this (with static methods, you do not need to create an object from the class; just call the methods on the name of the class, i.e. 'KeyboardInput.update();' or 'if ("enter".equals(KeyboardInput.key))'):
import greenfoot.*;
import java.util.List;

public class KeyboardInput
{
    public static String key;
    private static List<String> downKeys = new java.util.ArrayList<String>();;

    public static void update()
    {
        // remove past pressed keys that have been released
        for (int i=downKeys.size()-1; i>=0; i--) if (Greenfoot.isKeyDown(downKeys.get(i))) downKeys.remove(i);
        // get new key (if any)
        key = Greenfoot.getKey();
        // exit if no key detected
        if (key == null) return;
        // clear 'key' if detected key is in key pressed list
        for (String s : downKeys) if (key.equals(s))
        {
            key = null;
            break;
        }
    }
}
TinyTertle TinyTertle

2016/4/8

#
Ummm, isn't downKeys an empty ArrayList? Also, doesn't this only support one key being held down at a time?
danpost danpost

2016/4/8

#
TinyTertle wrote...
Ummm, isn't downKeys an empty ArrayList? Also, doesn't this only support one key being held down at a time?
Oops. Forgot to include the line to add to the list. Insert after line 22:
if (key != null) downKeys.add(key);
TinyTertle TinyTertle

2016/4/8

#
I really like the idea of keeping the down keys in an array! This should work. Thanks for the help!
You need to login to post a reply.