Есть вещи, которые не соответствуют вашему коду, по крайней мере, я так думаю.
Вы всегда перемещаете игрока на его новую позицию.Вы проверяете, касается ли он границ.Если он касается границ, вы перемещаете его на один пиксель вверх и на один пиксель влево только для того, чтобы переместить его на 7 пикселей в выбранном направлении.Поэтому внутри 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.
- use
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
}
Вам это поможет?