我在C#中做了类似游戏的东西,其中角色是一个图片框,它正在使用箭头键移动。我希望他在遇到坚固物体时停下来(我使用隐形方形面板来定义禁区)但我使用的代码使他在与面板接触时向相反的方向移动并按下不同的键。 / p>
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);
}
答案 0 :(得分:0)
为了使对象完全停在禁区,您必须根据区域边界和自己的大小设置其位置。对于左右键,这将是:
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);
此逻辑必须相应地应用于垂直方向。
使可见区域可见以进行测试。
答案 1 :(得分:0)
我终于做到了。通过添加
来解决问题
this.value = {val: val};
在每个动作关键动作中。更具体地说:
playerBox.Location = new Point(x, y);