Search code examples
c#animationtimerticker

C# timers for moving objects


I have 4 dogs who're racing, I need to move them across the form but they don't move gradually, they start out at the starting line and immediately teleport to the finish line, without moving in between. With every timer tick, their location.X is incremented.

Do I need one timer or 4? I currently have one, and its interval is set to 400.

This is the relevant code:

private void btnRace_Click(object sender, EventArgs e)
{   
    btnBet.Enabled = false;
    timer1.Stop();
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{   while (!isWon)
    {
        for (i = 0; i < Dogs.Length; i++) // there are four dogs
        {                    
            if (Dogs[i].Run()) // Run() returns true if full racetrack is covered by this dog
            {
                Winner = i + 1;
                isWon = true;

                MessageBox.Show("We have a winner! Dog #" + Winner);

                break;
            }
        }
}

And in the Dog class:

public bool Run()
{               
    Distance = 10 + Randomizer.Next(1, 4);
    p = this.myPictureBox.Location;
    p.X += Distance ;            
    this.myPictureBox.Location = p;

    //return true if I won the game
    if (p.X >= raceTrackLength)
    {
        return true ;
    }
    else
    {
        return false ;
    }
}

The dogs only appear to move one step and then immediately show up on the finish line. What am I doing wrong?


Solution

  • Remove While loop from timer1_Tick method. This method runs every 400 ms, but in your case at first launch it waits until one dog wins.

    Also you should stop the timer after one of dogs win.

    private void timer1_Tick(object sender, EventArgs e)
    {   
        for (i = 0; i < Dogs.Length; i++) // there are four dogs
        {                    
            if (Dogs[i].Run()) // Run() returns true if full racetrack is covered by this dog
            {
                Winner = i + 1;
                isWon = true;
                timer1.Stop();
                MessageBox.Show("We have a winner! Dog #" + Winner);
                break;
            }
        }
    }