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

2014/11/6

Help moving 1 tile at a time.

mullac51 mullac51

2014/11/6

#
Currently my object is moving constantly when i hold down whichever arrow key. How do I make it move a set distance each time it is pressed? Thanks
Alwin_Gerrits Alwin_Gerrits

2014/11/6

#
You can use either 'move' or 'setLocation'. Do I get it right that you want the object to move just once instead of constantly when a arrow key is hit?
Alwin_Gerrits Alwin_Gerrits

2014/11/6

#
So if you're holding down an arrow the object will still move only once instead of as long as the arrow key gets pressed?
danpost danpost

2014/11/7

#
The best way is to add an instance boolean field to the class, similar to how firing was described at the bottom of this discussion page. You will, however, need to use a combination of checks (one for each key):
// with instance boolean field
private boolean directionKeyDown; // initial default value is 'false'
// in act or method it calls
boolean leftDown = Greenfoot.isKeyDown("left");
boolean rightDown = Greenfoot.isKeyDown("right");
boolean upDown = Greenfoot.isKeyDown("up");
boolean downDown = Greenfoot.isKeyDown("down");
if (directionKeyDown != (leftDown || rightDown || upDown || downDown) &&
    (directionKeyDown = !directionKeyDown))
{
    int dx = 0, dy = 0;
    if (rightDown)  dx++;
    if (leftDown) dx--;
    if (upDown) dy--;
    if (downDown) dy++;
    setLocation(getX()+dx, getY()+dy);
}
You need to login to post a reply.