1 回答
TA贡献1826条经验 获得超6个赞
有一种观点与你的代码不正确,至少我认为是这样。
你总是把球员移动到他的新位置。你一定要检查他是否触及了界限。如果他触及边界,你把他向上移动一个像素,向左移动一个像素,只是为了将他移动到7个像素到所选的direktion中。因此,在你检查他是否触及边界的地方,你必须中断,不要执行设置新位置的其余代码。一个简单的将完成这项工作。
if
return;
如果按下一个键,你将进行边界检查,如果玩家没有触及边界,你将移动玩家。这是错误的顺序。你必须检查玩家在移动后是否会触及边界,只有当他不会触摸边界移动他时。否则,你会把他移入边界,再也不把他赶出去。
所以这是你的代码和一些更正:
private void HorrorForm_KeyDown(object sender, KeyEventArgs e)
{
int x = player.Location.X;
int y = player.Location.Y;
if (e.KeyCode == Keys.D)
x += 7;
if (e.KeyCode == Keys.A)
x -= 7;
if (e.KeyCode == Keys.S)
y += 7;
if (e.KeyCode == Keys.W)
y -= 7;
var tempPlayerPosition= player.Bounds; // get the players position and remember it temporary
tempPlayerPosition.X = x; // change the players temporary pisition to the new one that it will have after the move
tempPlayerPosition.Y = y;
//check if the play would touch the boundyries if we use the new temporary pisition
if (tempPlayerPosition.IntersectsWith(openspot1.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot2.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot3.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot4.Bounds))
{
return; //if he would touch the boundary, then do nothing
}
player.Location = new Point(x, y); //if he would not touch the boundary, move him to his new location
}
但也许你也想
防止在按下不是 W、S、A 或 D 的键时执行代码(即使他没有改变任何值)。
使用而不是这样使它更具可读性。
switch
if
而不是每次都写数字7,使用局部变量,所以如果将来会改变,你只需要改变一个值。
所以我的建议是这样的:
private void HorrorForm_KeyDown(object sender, KeyEventArgs e)
{
var oneStep = 7; // define the amount of pixel the player will be moved
var tempPlayerPosition = player.Bounds;// get the players position and remember it temporary
switch (e.KeyCode) // check which key was presses
{
case Keys.D:
tempPlayerPosition.X += oneStep; // move right
break;
case Keys.A:
tempPlayerPosition.X -= oneStep; // move left
break;
case Keys.S:
tempPlayerPosition.Y += oneStep; // move down
break;
case Keys.W:
tempPlayerPosition.Y -= oneStep; // move up
break;
default: // you may wan't to do nothing if there any other key presses...
return;
}
//check if the play would touch the boundyries if we use the new temporary pisition
if (tempPlayerPosition.IntersectsWith(openspot1.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot2.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot3.Bounds) ||
tempPlayerPosition.IntersectsWith(openspot4.Bounds))
{
return; //if he would touch the boundary, then do nothing
}
player.Location = new Point(tempPlayerPosition.X, tempPlayerPosition.Y); //if he would not touch the boundary, move him to his new location
}
这对你有帮助吗?
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报