Ответ 1
Анимация и WinForms, как правило, не являются простыми. Обычно программисты настраивают игровой цикл. Игровой цикл выполняет три функции: выбор пользовательского ввода, обновление новой позиции спрайтов, а затем рисование спрайтов на экране.
using System.Threading;
public partial class Form1
{
private Timer _timer;
private Dog _dog1, _dog2, _dog3, _dog4;
public void InitializeComponent()
{
SetupDogs();
// Every quarter of a second, run the function GameLoop
_timer = new Timer(GameLoop, null,
TimeSpan.FromSeconds(0.25),
TimeSpan.FromSeconds(0.25));
}
private void SetupDogs()
{
_dog1 = new Dog(PictureBoxDog1);
_dog2 = new Dog(PictureBoxDog2);
_dog3 = new Dog(PictureBoxDog3);
_dog4 = new Dog(PictureBoxDog4);
}
public void GameLoop(object state)
{
GetUserInput();
Update();
Draw();
}
public void GetUserInput()
{
// You don't need this now. But if you need to
// process user input later, you can do it here.
//
// e.g. if Last key
// pressed was arrow-left or
// arrow-right etc.
}
public void Update()
{
_dog1.Update();
_dog2.Update();
_dog3.Update();
_dog4.Update();
}
public void Draw()
{
// Draw on the main UI thread
Dispatcher.BeginInvoke(() =>
{
_dog1.Draw();
_dog2.Draw();
_dog3.Draw();
_dog4.Draw();
});
}
}
Затем ваш класс Dog выглядит так. Он должен Update
его местоположение каждый раз, когда таймер тикает, а затем нарисовать его положение:
public class Dog
{
bool _isRunning = true;
Point Location { get; set; }
Point NextLocation { get; set; }
PictureBox PictureBoxDog { get; set; }
public Dog(PictureBox pictureBox)
{
PictureBoxDog = pictureBox;
Location = GetRandomLocation();
NextLocation = GetRandomLocation();
}
private Point GetRandomLocation()
{
var random = new Random();
return new Point(random.Next(800), random.Next(800));
}
public void Update()
{
// Calculates the new coordinates for a dog
// The dog starts from a random position, and is
// given a new random position to run towards.
// If the dog has arrived at the new random position, then
// give the dog a new random position to run to again
if (NextLocation.X == Location.X && NextLocation.Y == Location.Y)
{
NextLocation = GetRandomLocation();
}
if (_isRunning)
{
// Move the dog closer to its destination
// dx and dy can be -1, 0, or 1
var dx = Math.Sign(NextLocation.X - Location.X);
var dy = Math.Sign(NextLocation.Y - Location.Y);
Location = new Point(Location.X + dx, Location.Y + dy);
}
}
public void Draw()
{
PictureBoxDog.Location = Location;
}
}