当图片框与另一个对象碰撞时,如何阻止它进一步移动?
本文关键字:何阻止 进一步 移动 碰撞 一个对象 | 更新日期: 2023-09-27 18:16:04
我用c#制作了一个类似游戏的东西,其中角色是一个图片框,它正在使用箭头键移动。我希望他在遇到固体物体时停下来(我使用不可见的正方形面板来定义禁止区域),但是我使用的代码使他在与面板接触时朝相反的方向移动,而我按了不同的键。
if (e.KeyCode == Keys.Right)
{
j_figure = 2;
x += velocity;
if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
x -= velocity - 10;
playerBox.Location = new Point(x, y);
}
else if (e.KeyCode == Keys.Left)
{
j_figure = 1;
x -= velocity;
if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
x += velocity + 10;
playerBox.Location = new Point(x, y);
}
else if (e.KeyCode == Keys.Up)
{
j_figure = 3;
y -= velocity;
if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
y += velocity + 10;
playerBox.Location = new Point(x, y);
}
else if (e.KeyCode == Keys.Down)
{
j_figure = 0;
y += velocity;
if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
y -= velocity - 10;
playerBox.Location = new Point(x, y);
}
我终于做到了。这个问题通过添加
解决了。playerBox.Location = new Point(x, y);
里面的每一个动作键动作。更具体地说:
if (e.KeyCode == Keys.Right)
{
j_figure = 2;
x += velocity;
playerBox.Location = new Point(x, y);
if (playerBox.Bounds.IntersectsWith(panel1.Bounds))
{
x = panel1.Left - playerBox.Width;
}
else if (playerBox.Bounds.IntersectsWith(panel2.Bounds))
{
x = panel2.Left - playerBox.Width;
}
}
...
// code for other directions
...
// again but this time outside the KeyCode if statements
playerBox.Location = new Point(x, y);
}
为了使停在禁止区域的对象,您必须根据区域边界和其自身的大小设置其位置。对于左键和右键,这将是:
if (e.KeyCode == Keys.Right) {
j_figure = 2;
x += velocity;
if (playerBox.Bounds.IntersectsWith(panel1.Bounds)) {
x = panel1.Left - playerBox.Width - 1;
} else if (playerBox.Bounds.IntersectsWith(panel2.Bounds)) {
x = panel2.Left - playerBox.Width - 1;
}
} else if (e.KeyCode == Keys.Left) {
j_figure = 1;
x -= velocity;
if (playerBox.Bounds.IntersectsWith(panel1.Bounds)) {
x = panel1.Right + 1;
} else if (playerBox.Bounds.IntersectsWith(panel2.Bounds)) {
x = panel2.Right + 1;
}
} ...
playerBox.Location = new Point(x, y);
此逻辑必须应用于相应的垂直方向。
使不可见的区域在测试中可见