Reputation: 1791
I'm making a very simple, spaceinvaders-style game. Currently, I have a fire method, set up to respond to the spacebar, like so:
case VK_SPACE:
tank.Fire();
break;
And the fire method, which makes off screen bullets appear behind a tank and then shoot them upward.
void Tank::Fire() {
//Moves bullets to behind tank.
bullets[bulletCount].SetPos(Vector2D (tank_pos.x+20, tank_pos.y+20));
//Sets their speed vector in motion.
bullets[bulletCount].SetSpeed(Vector2D (0, -350));
bulletCount++; //Increment the current bullet to be used.
}
The problem is one physical hit of the spacebar fires more than one at a time. How would one ensure that only one fires per press?
Upvotes: 0
Views: 496
Reputation: 6208
How are you capturing keyboard input? If this is just a loop that is checking the key state have a boolean that represents weather or not this is a new key down or not, then clear it when you notice the key isn't down any more. If you are worried about your OS's auto repeat then you want to look into debouncing, the basic idea is you capture the time you get the key down event then compare against the time future key down events occur so that you can rate limit them.
Upvotes: 2
Reputation: 22562
Currently, your code is probably doing something like "shoot while space is pressed". What you want is "press if space is pressed but was not pressed the frame before".
So, basically, you have to save the state of space from frame to frame and check whether space was pressed or not the frame before.
Upvotes: 1