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

2022/2/3

how do I make it so I only shoot 1 bullet when space is pressed?

NUKES NUKES

2022/2/3

#
So I made a Method in my Shooter Class which adds a new object when Space is Pressed, but it creates a whole lot of bullets. I only want 1 bullet to be shot when Spacebar is pressed, but I am not sure how I can make that happen.
public void shoot()
    {
     getWorld().addObject(new bullet(), getX(), getY()); 
    }
and then further down on the class:
if (Greenfoot.isKeyDown("space"))
            {
          shoot();
         }
danpost danpost

2022/2/3

#
NUKES wrote...
So I made a Method in my Shooter Class which adds a new object when Space is Pressed, but it creates a whole lot of bullets. I only want 1 bullet to be shot when Spacebar is pressed, but I am not sure how I can make that happen.
Add a boolean to track the state of the space bar:
private boolean spaceKeyDown;

// action code
if (spaceKeyDown != Greenfoot.isKeyDown("space")) // detect change in state of space key
{
    spaceKeyDown = ! spaceKeyDown; // tracking state of space key
    if (spaceKeyDown) shoot();
}
NUKES NUKES

2022/2/3

#
works perfectly, thank you very much!
You need to login to post a reply.