SFML community forums

Help => General => Topic started by: krej on May 24, 2010, 02:40:42 am

Title: How can I make it so they can't hold down a button and spam?
Post 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.
Title: How can I make it so they can't hold down a button and spam?
Post by: Spodi on May 24, 2010, 07:36:41 am
You add some kind of delay counter.

Code: [Select]

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).
Title: How can I make it so they can't hold down a button and spam?
Post by: Nexus on May 24, 2010, 11:06:22 am
To measure time, you can use sf::Clock. In case you have a constant framerate, you may also want to count frames.
Title: How can I make it so they can't hold down a button and spam?
Post by: Kingdom of Fish on May 24, 2010, 12:47:43 pm
Or you can switch to using events.
Title: How can I make it so they can't hold down a button and spam?
Post by: krej on May 25, 2010, 01:49:30 am
Quote from: "Kingdom of Fish"
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:

Code: [Select]

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);
  }
}
Title: How can I make it so they can't hold down a button and spam?
Post by: Spodi on May 25, 2010, 03:46:46 am
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.