I'm having some trouble simulating bullets in my 2D shooter. I want similar mechanics to Megaman, where the user can hold down the shoot button and a continues stream of bullets are fired but with a slight delay. Currently, when the user fires a bullet in my game a get an almost laser like effect. Below is a screen shot of some bullets being fired while running and jumping.
In my update method I have the following:
if(gc.getInput().isKeyDown(Input.KEY_SPACE) ){
bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() + 17));
}
Then I simply iterate through the array list increasing its x value on each update.
Moreover, pressing the shoot button (Space bar) creates multiple bullets instead of just creating one even though I am adding only one new bullet to my array list. What would be the best way to solve this problem?
Answer
You can add a little timer:
if(gc.getInput().isKeyDown(Input.KEY_SPACE) &&
gameTime.getTimeMS() - shootTime > shootDelayInMilliseconds) {
shootTime = gameTime.getTimeMS();
bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() + 17));
}
Basically you are noting the last time your character shot, then ensuring that enough time has passed before shooting again.
As for adding multiple bullets to the array list, it's doing this because you likely can't press the space bar fast enough to only have the space bar pressed for one frame. Each update you're adding one bullet. Add the delay like above will likely solve that problem. If you want to have a longer delay before you start repeating shots, you can doing something like:
if(gc.getInput().isKeyDown(Input.KEY_SPACE) && !previousInput.isKeyDown(Input.KEY_SPACE)) {
startShootTime = gameTime.getTimeMS();
}
if(gc.getInput().isKeyDown(Input.KEY_SPACE) &&
gameTime.getTimeMS() - shootTime > shootDelayInMilliseconds &&
gameTime.getTimeMS() - startShootTime > initalShootDelayInMilliseconds ) {
shootTime = gameTime.getTimeMS();
bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() + 17));
}
Where initalShootDelayInMilliseconds
is the time before holding the space bar causes repeated shots and shootDelayInMilliseconds
is the time between each repeated shot thereafter. This is similar to the keyboard input for many text editors, holding a key for a certain amount of time will cause that key to repeat at a (often shorter) delay rate.
No comments:
Post a Comment