C # - Предотвращение выхода из рамки изображения - PullRequest
0 голосов
/ 01 февраля 2019

У меня есть поле для картинок с именем player и 4 поля для картинок, которые действуют как границы в начале игр.У меня есть этот код, который выполняется при нажатии клавиши:

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;

            if (player.Bounds.IntersectsWith(openspot1.Bounds) || player.Bounds.IntersectsWith(openspot2.Bounds) || player.Bounds.IntersectsWith(openspot3.Bounds) || player.Bounds.IntersectsWith(openspot4.Bounds))
            {
                player.Location = new Point(player.Location.X - 1, player.Location.Y - 1);
            }

            player.Location = new Point(x, y);
        }

Как мне переместить игрока, но не дать ему покинуть границы?

a

1 Ответ

0 голосов
/ 01 февраля 2019

Есть вещи, которые не соответствуют вашему коду, по крайней мере, я так думаю.

  1. Вы всегда перемещаете игрока на его новую позицию.Вы проверяете, касается ли он границ.Если он касается границ, вы перемещаете его на один пиксель вверх и на один пиксель влево только для того, чтобы переместить его на 7 пикселей в выбранном направлении.Поэтому внутри if, где вы проверяете, касается ли он границы, вы должны прервать ее и не выполнять остальную часть кода, который устанавливает новую позицию.Простой return; сделает эту работу.

  2. Если нажата клавиша, вы выполняете проверку границы, если игрок не касается границ, вы перемещаете игрока.Это неправильный порядок.Вы должны проверить, будет ли игрок касаться границы после хода, и только если он не коснется границы, передвиньте его.В противном случае вы переместите его в границу и больше никогда его не выберете.

Итак, вот ваш код с некоторыми исправлениями:

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
}

Вам это поможет?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...