Martin1993-03
Martin1993-03

Reputation: 127

Timers and animation

I have a problem with animating missile move in my windows forms application. I'd like the missile to move every 0,5 second by five. Everytime I run my application I can't see it because I use space to shoot the missile then I don't see any animation, just missile appearing at the bottom of the window. I tried threading and with thread.Sleep(1) it works fine but I heard that timers are better for it.

My code looks like that:

this.Controls.Add(missile);
System.Timers.Timer t1 = new System.Timers.Timer();
t1.Interval = 500;
t1.Start();
while (missile.Location.Y > 0)
{
    missile.Location = new Point(missile.Location.X, missile.Location.Y - 5);
}
t1.Stop();

Upvotes: 1

Views: 1175

Answers (1)

Sedat Kapanoglu
Sedat Kapanoglu

Reputation: 47660

You need to put the code inside Timer class's Elapsed event like:

this.Controls.Add(missile);
System.Timers.Timer t1 = new System.Timers.Timer();
t1.Interval = 500;
t1.Elapsed += (sender, args) => 
{
  if (missile.Location.Y > 0)
  {
    missile.Location = new Point(missile.Location.X, missile.Location.Y - 5);
  }
};
t1.Start();

Upvotes: 2

Related Questions