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

2011/3/10

Method for moving around 1 step around grid each time a key is pressed?

hesh hesh

2011/3/10

#
Hey there! I'm new on Greenfoot and Java in general, trying to make a small puzzle game for a school project. I want to make a class that can move around a grid with 1 step each time a certain arrow key is pressed. I got the class to move around when I press the arrow keys, but it's on full speed and for as long as I keep the the button pressed. This is what I've got on the class' movement: public class Smarty extends Actor { /** * Allows smarty to act. */ public void act() { { processKeys(); } } /** * Handle keyboard input. */ public void processKeys() { if(Greenfoot.isKeyDown ("left")) { setLocation(getX() - 1, getY()); } else { setLocation(getX(),getY()); } if(Greenfoot.isKeyDown ("down")) { setLocation(getX(),getY() + 1); } else { setLocation(getX(),getY()); } if(Greenfoot.isKeyDown ("right")) { setLocation(getX() + 1,getY()); } else { setLocation(getX(),getY()); } if(Greenfoot.isKeyDown ("up")) { setLocation(getX(),getY() - 1); } else { setLocation(getX(),getY()); } } } Is there anything I should change or add to make this happen? Thank a lot in advance! hesh--
Builderboy2005 Builderboy2005

2011/3/10

#
Try using getKey(), it has quick key repeating turned on, which can slow things down and give you a delay String key = Greenfoot.getKey(); if("right".equals(key)){ setLocation(getX()+1,getY()); } if("left".equals(key)){ setLocation(getX()-1,getY()); } and so on also, you don't ever have you use setLocation(getX(),getY()) :P By the very nature of getX() and getY() you are already there!
hesh hesh

2011/3/10

#
That seems to be working! Thank you! Hahah! OK! :P For some reason I thought every 'if' method needed an 'else' line with it. My bad! ^^
You need to login to post a reply.