C# 使用线程移动PictureBox位置
我正在创造一个捉鸡蛋的游戏。在我的Panel子类中,我有以下代码C# 使用线程移动PictureBox位置,c#,multithreading,visual-studio,panel,picturebox,C#,Multithreading,Visual Studio,Panel,Picturebox,我正在创造一个捉鸡蛋的游戏。在我的Panel子类中,我有以下代码 public void startGame() { Thread t = new Thread(new ThreadStart(game)); t.Start(); } private void game() { bool run = true; int level = 1; while (run) {
public void startGame()
{
Thread t = new Thread(new ThreadStart(game));
t.Start();
}
private void game()
{
bool run = true;
int level = 1;
while (run)
{
Egg egg = dropper.selectEgg();
int speed = dropper.getSpeed(level);
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate {
this.Controls.Add(egg);
egg.setInitialLocation(dropper.selectPosition());
int x = egg.Location.X;
int y = egg.Location.Y;
while (y <= 1000)
{
egg.setCurrentLocation(x, dropper.drop(egg, speed));
y = egg.Location.Y;
}
}));
}
else
{
this.Controls.Add(egg);
egg.setInitialLocation(dropper.selectPosition());
int x = egg.Location.X;
int y = egg.Location.Y;
while (y <= 1000)
{
egg.setCurrentLocation(x, dropper.drop(egg, speed));
y = egg.Location.Y;
}
}
Thread.Sleep(3000);
}
}
但不知怎么的,我没有看到任何鸡蛋掉落。我猜这是线程访问PictureBox子类的问题?但我似乎在网上找不到任何解决办法
提前非常感谢。您可以在主UI线程上调用
drop
。这将快速运行一个循环,该循环将递增y
,直到大于1000。当循环运行时,用户界面无法更新,因此当drop
完成时,您将看到屏幕底部的鸡蛋,用户界面可以再次运行其消息循环
解决方案是将
drop
更改为仅递减y
一次,然后将控制权返回到游戏
循环。你必须移动y抱歉,我有点困惑。在drop()中,我只是将其设置为返回y位置。在game()中,我添加了egg.setCurrentLocation()。它仍然不起作用。我现在明白了。稍后我将用答案再次更新代码。非常感谢你!
public int drop(Egg egg, int speed)
{
int y = egg.Location.Y;
y += speed;
return y;
}