【问题标题】:Move PictureBox location with threading使用线程移动 PictureBox 位置
【发布时间】:2011-11-30 05:02:38
【问题描述】:

我正在创建一个丢鸡蛋的接球游戏。在我的 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;
    }

但不知何故,我没有看到任何 Egg 对象掉落。我猜这是线程访问 PictureBox 子类的问题?但我似乎无法在网上找到任何解决方案。

非常感谢您。

【问题讨论】:

    标签: c# multithreading visual-studio panel picturebox


    【解决方案1】:

    您在主 UI 线程上调用 drop。这会快速运行一个循环,该循环递增 y 直到 > 1000。在此循环运行时 UI 无法更新,所以当drop 完成并且 UI 可以运行时,您将看到的只是屏幕底部的鸡蛋它的消息再次循环。

    解决方案是将drop 更改为只减少一次y,然后将控制权返回给您的game 循环。您还必须将 y &lt;= 1000 检查移至此循环。


    更新:

    您的“步骤”是 while( run ) 循环的迭代 - 这就是您拥有 Sleep 来控制动画的地方。您只能在每个“步骤”上对 egg.Location.Y 进行一次更新 - 不要在每个“步骤”上运行整个 while( y &lt;= 1000 ) 循环。

    【讨论】:

    • 对不起,我有点困惑。在 drop() 中,我只是将其设置为返回 y 位置。在 game() 中,我添加了 egg.setCurrentLocation()。它仍然无法正常工作。
    • 我现在明白了。我稍后会用答案再次更新代码。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2012-11-15
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多