Skip to main content
GameDev.net gamedev.net
🔒 Locked

Help with C# XNA/Monogame

Started by SpyGlobe Jul 16, 2015 at 2:23 AM 4 replies 3.6k views
Original Post
SpyGlobe
SpyGlobe

I need the character to be able to shoot fireballs only every 12 seconds. But I can still shoot before 12 seconds and I don't want that. So when I shoot a fireball I try to record it as the current GameTime.ElapsedGameTime value but it's not working.

here is the code


// Create a readonly variable which specifies how often the user can shoot. 

 private static readonly TimeSpan ShootInterval = TimeSpan.FromSeconds(12);

// Keep track of when the user last shot. Or null if they have never shot in the current session.

        private TimeSpan? LastFireballShot;


private void UpdateFireball(GameTime theGameTime, KeyboardState aCurrentKeyboardState)
        {
            foreach (Fireball aFireball in mFireballs)
            {
                aFireball.Update(theGameTime);
            }

            if (aCurrentKeyboardState.IsKeyDown(Keys.RightControl) == true && mPreviousKeyboardState.IsKeyDown(Keys.RightControl) == false)
                  

            {
//the user is trying to shoot

                if (LastFireballShot == null || theGameTime.ElapsedGameTime - (TimeSpan)LastFireballShot >= ShootInterval)
                {

// Allow the user to shoot because he either has not shot before or it's been 1 second since the last shot.

                    ShootFireball();
                    
                }

            }
Eck
Eck

Use the debugger to look at the values of LastFireballShot, and theGameTime.ElapsedGameTime., and Shoot Interval. If you're using Visual Studio put the cursor there and hit F9 to set a breakpoint. Then use the Watch or Locals window to inspect the values of the variables.

Also, you don't need to cast the nullable LastFireballShot to a TimeSpan. Instead of (TimeSpan)LastFireballShot, write LastFireballShot.Value.

- Eck

Programmer16
Programmer16
ElapsedGameTime measures time between frames, so this isn't going to work how you want. I'm not at my PC, so I can't post a sample, but you're going to want to use ElapsedGameTime to either count up or down.
Dave Hunt
Dave Hunt

Instead of ElapsedGameTime, use TotalGameTime. TotalGameTime is the time since the game started rather than the frame elapsed time.

Programmer16
Programmer16

Based on your code, Dave Hunt's solution is actually much simpler - you just need to swap ElapsedGameTime out for TotalGameTime. I have a "delay timer" class set up in my library, so counting up or down was my first thought.

SpyGlobe
SpyGlobe

Wow I can't believe I fixed this problem I was about to give up. Thanks everyone

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.