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

2019/12/4

Problem with press key

Paciman Paciman

2019/12/4

#
I've been stuck for a moment now on how to change the gravity definitively when i press space. Because the issue i have right now is that when i press space my charackter changes gravity but if i don't push the space key he falls. I want it to change definitively but i can't find an code on the internet for that. I hope u guys can help me ^^
Paciman Paciman

2019/12/4

#
That's my code to change gravity if that helps you public void move() { int dx=5, dy=10; if(Greenfoot.isKeyDown("space")) { dy=dy*(-1); } if (dx != 0 && dy != 0) { setLocation(getX()+dx, getY()+dy); }
danpost danpost

2019/12/4

#
Try:
int dx = 5, dy = 10;
boolean spaceDown;

public void move()
{
    if (spaceDown != Greenfoot.isKeyDown("space"))
    {
        spaceDown = !spaceDown;
        if (spaceDown) dy = -dy;
    }
    setLocation(getX()+dx, getY()+dy);
}
Paciman Paciman

2019/12/4

#
danpost wrote...
Try:
int dx = 5, dy = 10;
boolean spaceDown;

public void move()
{
    if (spaceDown != Greenfoot.isKeyDown("space"))
    {
        spaceDown = !spaceDown;
        if (spaceDown) dy = -dy;
    }
    setLocation(getX()+dx, getY()+dy);
}
Okay it worked perfectly thanks ^^. Could you maybe explain just the code you just wrote down. I would really appreciate i dont like writing things I don't understand
danpost danpost

2019/12/4

#
Paciman wrote...
Could you maybe explain just the code you just wrote down. I would really appreciate i dont like writing things I don't understand
The first line was moved outside the method so the values can be retained (not reset every time the method is called). The second line was added to track the (last known) state of the "space" key. Line 6 checks to see if the state of the key had changed (either just pressed or just released). Line 8 updates the tracking field when a change in the state of the key is detected. Line 9 reverses gravity if the new state is the down state (just pressed). You know what line 11 does.
You need to login to post a reply.