移动时如何将图片框保留在表格中?

时间:2013-04-26 15:29:00

标签: c# winforms picturebox

我正在尝试制作一款游戏,但我在这里遇到了一些问题...... 我正在用箭头键移动一个图片框,以避免其他图片框...问题是,当我按下左键太多次时,我的图片框移出了表单...我成功解决了这个问题右侧(通过另一个阻止图片框),但左侧版本仍然不起作用,我不知道为什么......

以下是代码:

if (pictureBox7.Bounds.IntersectsWith(pictureBox1.Bounds))
            switch (e.KeyCode)
            {
                case Keys.Escape: Application.Exit(); break;
                case Keys.P: timerkunai1.Enabled = false;
                    timerkunai2.Enabled = false; timerkunai3.Enabled = false;
                    timerkunai4.Enabled = false; timerninja.Enabled = false;
                    timerlife.Enabled = false;
                    button3.Show(); break;
                case Keys.Right: i = 6; dx = 25; press = true; break;            
            }
        if (pictureBox8.Bounds.IntersectsWith(pictureBox1.Bounds))
            switch (e.KeyCode)
            {
                case Keys.Escape: Application.Exit(); break;
                case Keys.P: timerkunai1.Enabled = false;
                    timerkunai2.Enabled = false; timerkunai3.Enabled = false;
                    timerkunai4.Enabled = false; timerninja.Enabled = false;
                    timerlife.Enabled = false;
                    button3.Show(); break;
                case Keys.Left: i = 0; dx = -25; press = true; break;
            }
        else
            switch (e.KeyCode)
        {
            case Keys.Escape: Application.Exit(); break;
            case Keys.P: timerkunai1.Enabled = false;
                timerkunai2.Enabled = false; timerkunai3.Enabled = false;
                timerkunai4.Enabled = false; timerninja.Enabled = false;
                timerlife.Enabled = false;
                button3.Show(); break;
            case Keys.Left: i = 0; dx = -25; press = true; break;
            case Keys.Right: i = 6; dx = 25; press = true; break;
        }

2 个答案:

答案 0 :(得分:0)

您需要使用代码来检查图片框的边界是否在表单之外。如果图片框移动会使其超出界限,则阻止动作。 像这样的伪代码: if (pictureBoxZ + dx < 0 || pictureBoxZ + dx > pictureBoxZ.Parent.Width) { //Deny Motion }

答案 1 :(得分:0)

你的dx变量是否是PictureBox新位置的偏移量? 然后将Location.x限制为0:

 if (pictureBox1.Location.x + dx > 0)
     pictureBox1.Location += dx;

如果要限制为左右大小,请使用此代码:

if ((pictureBox1.Location.x + dx > 0) && (pictureBox1.Location.x + dx < this.Size.Width - pictureBox1.Size.Width))
     pictureBox1.Location += dx;