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

2016/1/9

Problem with shooting

... ...

2016/1/9

#
so i have a code and im making galaga and i need it too shoot only once per time i press "space" because if i hold space it rapidly shoots
public void shoot()
    {
       if("space".equals(Greenfoot.getKey()))  
       {
           getWorld().addObject (new ShipLaser(), getX(), getY());
       }
    }
TomazVDSN TomazVDSN

2016/1/9

#
could you try this ? public void shoot() { int x=0 if("space".equals(Greenfoot.getKey() && x=0)) { getWorld().addObject (new ShipLaser(), getX(), getY()); x =1 } }
danpost danpost

2016/1/9

#
You are currently using the state of the 'space' key for shooting. You need to use one of the changes in the state of the key (key pressed or key released) which requires you to be able to compare the last state of the key with the current state of the key. and then when a change occurs and it is currently in the state you want for shooting, shoot.
// instance field
private boolean spaceDown;

// the shoot method
public void shoot()
{
    if (spaceDown != Greenfoot.isKeyDown("space"))
    {
        spaceDown = !spaceDown;
        if (spaceDown)
        {
            getWorld().addObject(new ShipLaser(), getX(), getY());
        }
    }
}
You need to login to post a reply.