我有一个名为player的图片框和4个在游戏开始时充当边界的图片框。如果按下某个键,我会执行此代码:
private void HorrorForm_KeyDown(对象……
有一些观点与你的代码不一致,至少我是这么认为的。
你总是将玩家移动到他的新位置。你确实检查他是否触及边界。如果他触及边界,则向上移动一个像素,向左移动一个像素,然后将7个像素移动到所选择的方向。 所以在里面 if 在那里你检查他是否触及边界你必须中断并且不执行设置新位置的其余代码。一个简单的 return; 会做的。
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 }
但也许你也想
switch
所以我的推荐看起来像这样:
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 }
这对你有帮助吗?