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

2013/6/12

URGENT HELP

aheadinstead aheadinstead

2013/6/12

#
how do i make my actor move up or down by pressing the up and down key with the code keypress???????
Gevater_Tod4711 Gevater_Tod4711

2013/6/12

#
You can use the method Greenfoot.isKeyDown(String keyname). To make your actor move in the direction of the arrow keys you can use this code:
//you need to call this method from the act method of your class;
public void move() {
    if (Greenfoot.isKeyDown("up")) {
        setLocation(getX(), getY() - 1);
    }
    if (Greenfoot.isKeyDown("down")) {
        setLocation(getX(), getY() + 1);
    }
    if (Greenfoot.isKeyDown("left")) {
        setLocation(getX() - 1, getY());
    }
    if (Greenfoot.isKeyDown("right")) {
        setLocation(getX() + 1, getY());
    }
}
aheadinstead aheadinstead

2013/6/12

#
why not the keypress method?
Gevater_Tod4711 Gevater_Tod4711

2013/6/12

#
What is a keypress method? I think there is no such method in greenfoot. And using KeyListeners would be much more difficult.
aheadinstead aheadinstead

2013/6/12

#
public void checkKeypress() { if (Greenfoot.isKeyDown("up")) { turn(2); } if (Greenfoot.isKeyDown("down")) { turn(-2); }
danpost danpost

2013/6/12

#
You only need change what happens when the keys are down:
public void checkKeypress()
    {
        if (Greenfoot.isKeyDown("up")) 
        {
            setLocation(getX(), getY()-1);
        }
        if (Greenfoot.isKeyDown("down")) 
        {
            setLocation(getX(), getY()+1);
        }
}
You need to login to post a reply.