C# 如何将对象限制在形状的边界内

C# 如何将对象限制在形状的边界内,c#,winforms,C#,Winforms,我目前正在用C#Windows窗体制作一个太空入侵者类型的游戏。在创建用户控制的激光炮时,我希望他们左右移动,发射激光。这是我目前的运动代码: enter code here using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using

我目前正在用C#Windows窗体制作一个太空入侵者类型的游戏。在创建用户控制的激光炮时,我希望他们左右移动,发射激光。这是我目前的运动代码:

enter code here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Move
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_KeyDown(object sender, KeyEventArgs e)
    {

    }

    private void pictureBox1_Click(object sender, EventArgs e)
    {

    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        int i;

        for (i = 0; i < 500; i++)
        {

            if (e.KeyCode == Keys.Up)
            {
                pictureBox1.Location = new Point(pictureBox1.Left - 1);
                Application.DoEvents();
                System.Threading.Thread.Sleep(10);
            }

            if (e.KeyCode == Keys.Down)
            {
                pictureBox1.Location = new Point(pictureBox1.Left + 1);
                Application.DoEvents();
                System.Threading.Thread.Sleep(10);
            }




        }
      }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}
}

比如我如何得到整个形状的正确的X,Y坐标,这样我就可以告诉它向另一个方向移动,也可以让它移动

图片框留在表单中的最小X和Y位置为0

图片框可以到达的最大X是
Form.ClientSize.Width-pictureBox.Size.Width

图片框可以容纳的最大Y是
Form.ClientSize.Height-pictureBox.Size.Height


在if语句中检查所有这些内容。如果图片框的X或Y超出范围,请不要移动图片框,否则请移动它。

这有点令人困惑。你想按up(??)向右移动,直到你到达屏幕的末端,然后你想向上向左移动?你不应该在屏幕的一侧反弹,你应该坚持屏幕的一侧。只需根据容器的边界测试坐标,如果它带你出去,就不要移动。否则,我甚至不知道你如何期望人们能够再次向左移动,因为向上现在向右移动,向下做什么?小心使用
Application.DoEvents()
。它可能有严重的副作用。如果你认为你需要它,那么你在画画时就做错了。至于您的问题,只需检查您的对象在客户端
边界内的位置即可。为什么要新建点(300300)?您可以通过边界的宽度和高度以及@DonBoitnott关于
DoEvents
的绝对内容来检查边界。任何时候你需要
DoEvents
你可能做错了什么。@MattBurland是的,我知道这很奇怪,只是在我让它工作之前一直在尝试。我现在可能该换了。在这种情况下,上=右,下=左。很抱歉给你带来了混乱
if(pictureBox1.Location == new Point(300,300))
            {
                pictureBox1.Location = new Point(pictureBox1.Left - 1);
            }