Search code examples
c#xnamonogame

Projectile delay in shooting c# game


I have a game where I want the player to be able to shoot a laser with a delay on it. The code works but I'm wondering if I am going the right way about doing this.

I was wondering what is the proper way to add the delay?

I tried to include the code relevant to the question.

private double laserDelay;
private TimeSpan laserShootInterval = TimeSpan.FromSeconds(6);
laserDelay = laserShootInterval.TotalSeconds;

if (currentKeyState.IsKeyDown(Keys.Space))
{
    if(laserDelay == laserShootInterval.TotalSeconds)
    { 
          Shoot();
          laserDelay = laserDelay - laserShootInterval.TotalSeconds;
    }

}

UpdateLasers(graphics);


if(laserDelay < laserShootInterval.TotalSeconds)
{
      laserDelay++;
}

Solution

  • Presuming you are not using delta time (fixed amount of ticks per second) I would do it like so:

    int delay = 6 * ticksPerSecond; // ticks to delay for
    int cooldown = 0;
    
    public void loop()
    {
    
        if (currentKeyState.IsKeyDown(Keys.Space))
        {
            if(cooldown <= 0)
            { 
                  Shoot();
                  cooldown = delay
            }
    
        }
    
        UpdateLasers(graphics);
    
    
        if(cooldown > 0){
              cooldown -= 1;
        }
    }