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

2021/1/19

Help With Movement

Marethyu05 Marethyu05

2021/1/19

#
So I want my actor to move the amount I have specified when i press the key, but I only want the code to run once even if i'm holding down the button. I imagine that I need a variation of (isKeyDown) but haven't been able to find anything.
if (Greenfoot.isKeyDown("up"))
    {
        setLocation(getX(), getY() + -5);
    }
danpost danpost

2021/1/20

#
Marethyu05 wrote...
So I want my actor to move the amount I have specified when i press the key, but I only want the code to run once even if i'm holding down the button. I imagine that I need a variation of (isKeyDown) but haven't been able to find anything. << Code Omitted >>
You just need to incorporate a boolean field to track the state of the key:
private boolean upKeyDown;

public void act()
{
    if (upKeyDown != Greenfoot.isKeyDown("up")) // is state of key changed
    {
        upKeyDown = !upKeyDown; // new state
        if (upKeyDown) setLocation(getX(), getY()+5); // if new state is down, move
    }
}
Marethyu05 Marethyu05

2021/1/20

#
Thank you so much for the help.
You need to login to post a reply.