【问题标题】:How to keep an object moving within a picturebox C#如何保持对象在图片框内移动 C#
【发布时间】:2018-08-03 11:29:16
【问题描述】:

所以我有一个对象“播放器”,它也是一个图片框。 它使用键向左和向右移动。我希望它只能在图片框(屏幕)内移动,并且如果它碰到边缘就停止并且不能走出它。

这是我的尝试

        private void Game_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Right)
        {
            right = false;

            if (screen.Bounds.IntersectsWith(player.Bounds))
            {
              ???

            }
        }
        if (e.KeyCode == Keys.Left)
        {
            left = false;

        }
    }

有人可以帮忙吗?提前致谢。

【问题讨论】:

    标签: c# game-physics picturebox bounds


    【解决方案1】:

    如果我正确理解了这个问题,这样的事情应该可以工作。

    private void Game_KeyUp(object sender, KeyEventArgs e)
    {            
        int leftChange = 0;
        if (e.KeyCode == Keys.Right)            
            leftChange = 10;     
        if (e.KeyCode == Keys.Left)            
            leftChange = -10;
    
        // check right bound
        if ((player.Right + leftChange) > screen.Right)
            leftChange = (screen.Right - player.Width) - player.Left;
        // check left bound
        if ((player.Left + leftChange) < screen.Left)
            leftChange = screen.Left - player.Left;
    
        // move the player
        player.Left += leftChange;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多