Help with C# XNA/Monogame

Started by
4 comments, last by SpyGlobe 8 years, 9 months ago

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();
                    
                }

            }
Advertisement

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

EckTech Games - Games and Unity Assets I'm working on
Still Flying - My GameDev journal
The Shilwulf Dynasty - Campaign notes for my Rogue Trader RPG

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.

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

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.

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

This topic is closed to new replies.

Advertisement