如何在移动时将图片框保持在窗体中?

如何在移动时将图片框保持在窗体中?

问题描述:

我试图做一个单一的游戏,但我在这里得到了一个小问题... 我正在移动带箭头键的图片盒,以避免其他图片盒...问题是,我的图片盒移出当我按下左键太多次时,我就成功地解决了这个问题(通过阻塞另一个盒子),但左侧版本仍然不起作用,知道为什么...如何在移动时将图片框保持在窗体中?

下面是代码:

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; 
     } 

需要编写代码,以检查是否在PictureBox的边界是形式之外。如果图片框移动将导致它超出边界,则阻止移动。 类似这样的伪代码: if (pictureBoxZ + dx < 0 || pictureBoxZ + dx > pictureBoxZ.Parent.Width) { //Deny Motion }

您的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;