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

2024/5/28

I want to make my code work so that the code only runs when a key is pressed, and won't run if the key is being held down

toemilio toemilio

2024/5/28

#
Here is my code
double dy = 0; //is the value that is always being added
    //to our Y coord in setlocation
    double g = 0.5;//this is what is going to get ADDED 

 public void act()
    {
        setLocation( getX(),  (int) (getY() + dy) );  // hint in here as to how to get gravity working with the g and dy
}

public void flapFlap()
    {
        
        if (Greenfoot.getKey() == ("space"))
        {
            
            dy = -4;
            //when the space key is pressed flappys dy (gravity) is set to -4. when the g is less than 0 flappy goes up
        }
        else
        {
            dy = dy + g;
            //whenever the space key is not being pressed increase gravity by 0.5. when the g is greater than 0 flappy goes down
        }
        
    }
danpost danpost

2024/5/29

#
In line 13, your string comparison may never be true. It compares the String objects to see if they are the same object. That comparison does not care about the contents of the strings. You can compare the contents this way:
if ("space".equals(Greenfoot.getKey()))
However, I would reserve the getKey method for main menu and command control options. You can add a boolean and use isKeyDown to capture when the key is pressed:
/** new field */
private boolean spaceDown;

/** checking key */
if (spaceDown != Greenfoot.isKeyDown("space"))
{  // change in state of key
    spaceDown = !spaceDown; // record change in state
    // act on change (if going down)
    if (spaceDown)
    {
        dy = -4.5;
    }
}
dy = dy + g;
I move the last line outside the else block, removing the block (and adjusted the previous line to compensate). Gravity should be in effect at all times
toemilio toemilio

2024/5/29

#
Did this and it worked! Thanks!
You need to login to post a reply.