SFML community forums
Help => General => Topic started by: krej on May 24, 2010, 02:40:42 am
-
I'm trying to make a simple space invaders game, and I have this:
if ( App.GetInput().IsKeyDown(sf::Key::Space)) { /* shoot missile */ }
However, if you hold down space it spams the missiles. How do you get around this? I want it so that they have to press space each time they want to shoot a missile.
-
You add some kind of delay counter.
if (isKeyDown(Space) && (Time.Now - SHOOT_DELAY) > _lastShootTime) {
// Shoot
_lastShootTime = Time.Now;
}
So basically, every time they shoot, you mark down the time. When you check to shoot, you only let the shoot happen (and update the timer) if enough time has elapsed (SHOOT_DELAY).
-
To measure time, you can use sf::Clock. In case you have a constant framerate, you may also want to count frames.
-
Or you can switch to using events.
-
Or you can switch to using events.
I'd like to switch to events, but I tried that and there is only a small delay in shooting. Instead of it spamming nonstop, its *shoot shoot shoot* *slight delay* *shoot shoot shoot*
This is the code I have for events:
sf::Event Event;
while (App.GetEvent(Event)) {
if ( Event.Key.Code == sf::Key::Space ) {
sf::Sprite Missle(MissileImage);
Missile.SetPosition(Player.GetPosition());
Missile.SetRotation(Player.GetRotation());
missiles.push_back(Missile);
}
}
-
You will want to use polling unless you want people to shoot each time they press the button. Polling will allow you to check every frame if they can shoot, while events give you the system repeat rate.
Also, a time-based approach instead of frame-based approach is generally better since you can make your program frame-independent that way. I don't think there is much frame-based game development these days since people have various refresh rates, you want to allow low-end machines to simulate the gameplay the same even if the frame rate is below the target frame rate, and its a relatively cheap operation for modern systems.