Luke h
Luke h

Reputation: 337

Different functions different delays c#

I'm making a simple c# game similar to snake, and I have two moving aspects. I have a method to move both of them, however I want them to both move at different speeds. Here's a cut down version of the method I have now.

private async void mover()
{
    while (GlobalVar.Status == "alive")
    {
         if (GlobalVar.Direction == "up")
         {
              try { moveupp(GlobalVar.Row, GlobalVar.Column, "player"); }
              catch (System.IndexOutOfRangeException) { died(); }
         }
         if (GlobalVar.OppDirection == "up")
         {
              try { moveupp(GlobalVar.Row, GlobalVar.Column, "opp1"); }
              catch (System.IndexOutOfRangeException) { died(); }
         }
         await Task.Delay(500);
   }
}

Here, in the first IF statement, my character (player) is moving up, and in the second IF statement, the opponent (opp1) is moving up. These are working in sync with a 500 millisecond delay in between with the delay "await Task.Delay(500);". My question is, is there anyway they can both run together, with different delays in between? So the opp1 can move faster than the player? Many thanks in advance!

Upvotes: 0

Views: 128

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

I would use two different timers instead of delaying tasks. Also I would not use exceptions to control program flow:

private PlayerTimer_Tick(object sender, EventArgs e)
{
     if (GlobalVar.Status != "alive")
         return; // you can also stop timer in this case

     if (GlobalVar.Direction == "up")
     {
         if (GlobalVar.Column == 0)
             died();
         else
             moveupp(GlobalVar.Row, GlobalVar.Column, "player");  
     }
}

Also create timer for opp1 and set different intervals for these timers - 500 for player and another value for opp1.

Upvotes: 1

Related Questions