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

2014/1/30

Just because I'm a noob...

nickvcg nickvcg

2014/1/30

#
How would I go about making this only allow a key being held down to register as 1 action? Here's what I have: public void move() { if(Greenfoot.isKeyDown("up")){ setLocation(getX(), getY() - 1); } if(Greenfoot.isKeyDown("down")){ setLocation(getX(), getY() + 1); } if(Greenfoot.isKeyDown("right")){ setLocation(getX() + 1, getY()); } if(Greenfoot.isKeyDown("left")){ setLocation(getX() - 1, getY()); } } And from there I want to make it so that no matter what, even if the key is still down, it doesn't allow a held down key to count for more than action. How would I do that?
danpost danpost

2014/1/30

#
One way:
// instance field
private boolean arrowDown;
// method
public void move()
{
    boolean right = Greenfoot.isKeyDown("right");
    boolean left = Greenfoot.isKeyDown("left");
    boolean up = Greenfoot.isKeyDown("up");
    boolean down = Greenfoot.isKeyDown("down");
    if (arrowDown && !right && !left && !up && !down) arrowDown = false;
    if (arrowDown || (!right && !left && !up && !down)) return;
    arrowDown = true;
    if (right) setLocation(getX()+1, getY());
    if (left) setLocation(getX()-1, getY());
    if (down) setLocation(getX(), getY()+1);
    if (up) setLocation(getX(), getY()-1);
}
nickvcg nickvcg

2014/1/30

#
Awesome! Thank you! Just got started with this stuff in a CS1010 class at my school, but the class itself is moving at a dirt slow pace and I'm really enjoying myself with this stuff so I'm trying to learn it on my own on the side, as well as c++ to see what I can figure out on my own
You need to login to post a reply.