Question

A bit stuck on incrementing the player's score after 5 seconds. Eventually i would like to be able to use the same logic to increment the score by 'x' amount after all different time periods. At the moment, the score is being incremented by 10 but 60 times a second (due to the update method being called 60 times a second). This means the score ends up being 560 instead of just 10.

I was thinking of trying to use variables such as isPreviousScoreChanged and isCurrentScoreChanged, like when detecting if a button has been pressed and released, however this isn't working too well either.

I am using the Stopwatch class to keep track of the amount of seconds gone by since the start of the game.

the code is pretty much:

if (Stopwatch.ElapsedTicks == 5)
{
    playerScore += 10;
}

[I know it's possible to paste code in here but there isn't much to paste and it's quite simple what i've done so far]

thanks v much for reading everyone :-)

Was it helpful?

Solution

Do something like this:

if (timer > TimeSpan.Zero)
{
   timer -= gameTime.ElapsedGameTime;
   if (timer <= TimeSpan.Zero)
   {
       playerScore += 10;
       timer = TimeSpan.Zero;
   }
}

Of course you have to set timer = new TimeSpan(0, 0, 5);

OTHER TIPS

First - I recommend not using ticks, since one tick is a very small amount of time. Second - if updating every x seconds, using the modulus operator if more efficient.

if((Stopwatch.ElapsedMilliseconds%2000)==0){playerScore+=10}

In this example, the score should be updated every 2 seconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top