【发布时间】:2023-04-03 04:35:02
【问题描述】:
长期以来,我一直在挑战这个问题。简单地说,我想避免两个图片框之间的碰撞。当看到pictureBox2 时,pictureBox1 必须停止。但是,我确实设法通过 Intersect 做到了这一点。就像下面的代码一样;
private void method(PictureBox b)
{
if (pictureBox1.Bounds.IntersectsWith(b.Bounds)) {
movement = false;}
}
问题是按键。我正在使用 KeyDown(W, A, S, D) 移动图片框1,当我按住键时,相交代码工作得很好。但是当我一个个按到键时,它只是滑入了pictureBox2。我怎样才能避免这种情况?我确实尝试用布尔值来阻止它,但它没有用。我想我需要 if 语句,但我无法做出逻辑。寻找您的解决方案。提前致谢。
KeyDown 事件;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (movement == true)
{
int x = pictureBox1.Location.X;
int y = pictureBox1.Location.Y;
if (e.KeyCode == Keys.W) y -= chrspeed;
else if (e.KeyCode == Keys.A) x -= chrspeed;
else if (e.KeyCode == Keys.D) x += chrspeed;
else if (e.KeyCode == Keys.S) y += chrspeed;
pictureBox1.Location = new Point(x, y);
method(pictureBox2);
}
}
chrspeed 为 20;
KeyUp 事件;
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
movement = true;
}
【问题讨论】:
-
获取tour、阅读How to Ask和minimal reproducible example。
method实际上是一个方法的坏名。 -
请显示您的“按键”方法和更多相关内容(您显示的代码没有多大帮助)。
-
按键事件为空。我认为问题与 KeyPress 事件有关,这就是我提到的原因。 @PoulBak
-
你很幸运,它是一个接一个的步进失败。将矩形靠近在一起,然后设置断点并开始调试。您可能无法获得预期的事件。
-
方法只是为了澄清。如果你愿意,你可以称它为碰撞检查。它最初是 CLcheck。
标签: c# game-physics