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

2016/5/13

Semi-Auto Weapons

Cragster25 Cragster25

2016/5/13

#
Hello Everyone, I was wondering if someone can help me with something, I a creating a zombie survival game which will have a semi-automatic pistol where the bullet will get added each time the space key is pressed, I know how to have delays for my other weapons but that didn't work for the pistol. any suggestions.
danpost danpost

2016/5/13

#
Cragster25 wrote...
Hello Everyone, I was wondering if someone can help me with something, I a creating a zombie survival game which will have a semi-automatic pistol where the bullet will get added each time the space key is pressed, I know how to have delays for my other weapons but that didn't work for the pistol. any suggestions.
What delays are you using for the other weapons and what did you try for the pistol?
Cragster25 Cragster25

2016/5/13

#
Well I used a variable which I called delay, so when the delay equals a certain number it would add a bullet and then repeat. For the pistol I first thought about setting a high delay value but that didn't work. I then thought of a possible Boolean so the firing is true when the key is pressed but if it isn't then nothing happened, I might have a possible option that contains both features but will test it first and will reply the results.
danpost danpost

2016/5/14

#
Cragster25 wrote...
I might have a possible option that contains both features but will test it first and will reply the results.
You only need the boolean to track the state of the key. Anytime the boolean value does not coincide with the current state, a change in state has occurred and the field needs to be updated. Along with updating the field, you can check what the new state is and create a bullet on one of the two states:
// the instance field
private boolean pistolFired;

// in act or a method it calls
if (pistolFired != Greenfoot.isKeyDown("space")) // has key state changed?
{
    pistolFired = ! pistolFired; // save new state
    if (pistolFired) shootPistol(); // create bullet
}
I did not write out the code to create and add the bullet into the world, setting its direction or anything. All this would be done in a 'shootPistol' method or in place of the 'shootPistol' method call at line 8.
Cragster25 Cragster25

2016/5/14

#
I have manages to fix it by changing the variable I have set to be a minus and when the space isn't pressed it would reset so the pistol can then fire once again.
private int fireRate = 1;
private int fireDelay = 1;
      if (Greenfoot.isKeyDown("space")){
         fireRate -=1 ;
         if (fireRate==0){
           getWorld().addObject(new Bullet(),getX(),getY());
          }
        }
        else
        {
         fireRate = fireDelay(;
        }
You need to login to post a reply.