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

2011/3/10

Trouble using multiple key listeners

Maxident Maxident

2011/3/10

#
im trying to make a game where i can move something left and right at the bottom of the screen, and then shoot so hopefully using multiple buttons on the keyboard. only problem is i can only seem to get any one key to respond in my act() method i have something like: if("left".equals(Greenfoot.getKey())) { moveLeft(); } else if("right".equals(Greenfoot.getKey())) { moveRight(); } and i would have one for the shoot function aswell, atm that is asigned to mouse click. basically, the two methods moveLeft() and moveRight() work fine, and whichever one i put first (no matter what key it is assigned to) will work and the other won't. I tried putting them in seperate if statements, no luck.
Builderboy2005 Builderboy2005

2011/3/10

#
If you use GetKey() anywhere, it will be cleared when you access it, and so any uses of it after are likely not going to have any value at all in them. What you need to do is store the key value at the start: String key = Greenfoor.getKey(); if("left".equals(key)) { moveLeft(); } if("right".equals(key)) { moveRight(); } But, this doesn't allow for smooth movement, and you would still only be able to press 1 key at a time. Try using IsKeyDown() instead: if(Greenfoot.isKeyDown("left") { moveLeft(); } if(Greenfoot.isKeyDown("right") { moveRight(); }
Builderboy2005 Builderboy2005

2011/3/10

#
Hmmm methinks we need a way to delete our own posts :/
mjrb4 mjrb4

2011/3/11

#
I removed your duplicate reply :-) Builderboy is correct, isKeyDown() is the method you want to use here. The getKey method is more use in single key presses. As a general rule of thumb, if it's holding a key down for any length of time to complete an action (such as moving a character using the arrow keys) its isKeyDown() that you should use.
You need to login to post a reply.