使用线程移动PictureBox位置
本文关键字:PictureBox 位置 移动 线程 | 更新日期: 2023-09-27 18:16:15
我正在创建一个鸡蛋掉落的捕捉游戏。在Panel子类中,我有如下代码
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);
}
}
Egg是PictureBox的一个子类,我想改变它在循环上的位置,使它看起来像鸡蛋正在掉落。我用这个方法使用EggDropper子类:
public int drop(Egg egg, int speed)
{
int y = egg.Location.Y;
y += speed;
return y;
}
但不知怎么的,我没有看到任何蛋的物体掉下来。我猜这是访问PictureBox子类的线程的问题?但是我在网上似乎找不到任何解决办法。
非常感谢。
在主UI线程上调用drop
。这将快速运行一个循环,增加y
直到它> 1000。当这个循环运行时,UI不能更新,所以当drop
完成时,你将看到的是屏幕底部的鸡蛋,UI可以再次运行它的消息循环。
解决方案是将drop
更改为仅减少y
一次,然后将控制返回到game
循环。您必须将y <= 1000
复选框也移动到这个循环中。
更新:
你的"step"是while( run )
循环的迭代-这就是你有Sleep
来控制动画的地方。
egg.Location.Y
进行一次更新-不要在每个"步骤"上运行整个while( y <= 1000 )
循环。