简体   繁体   English

如何在 4 方向 2D 游戏中实现基于网格的运动?

[英]How to implement grid based movement in a 4 Direction 2D Game?

I'm working on a 4 Direction (up,down,left,right) 2D game and it'll be with grid based movement, yet i can't figure it out to work it out.我正在开发一个 4 方向(上、下、左、右)的 2D 游戏,它将使用基于网格的运动,但我无法弄清楚如何解决它。

public class Player: Character {公共 class 播放器:字符 {

/// <summary>
/// Overridin the characters update function, so that we can execute our own functions
/// </summary>
protected override void Update()
{
    //Executes the GetInput function
    GetInput();



    base.Update();
}

/// <summary>
/// Listen's to the players input
/// </summary>
private void GetInput()
{
    direction = Vector2.zero;





    //Movement
    if (Input.GetKey(KeyCode.UpArrow))
    {
        direction += Vector2.up;
    }
    else if (Input.GetKey(KeyCode.LeftArrow))
    {
        direction += Vector2.left;
    }
    else if (Input.GetKey(KeyCode.DownArrow))
    {
        direction += Vector2.down;
    }
    else if (Input.GetKey(KeyCode.RightArrow))
    {
        direction += Vector2.right;
    }

} }

You can do it two ways:你可以通过两种方式做到这一点:

  1. You could just add a value on x and y property and make sure that they don't have floating numbers on them.您可以在 x 和 y 属性上添加一个值,并确保它们没有浮动数字。 ie: x + 1 on going right, x - 1 on going left, etc.即:x + 1 向右走,x - 1 向左走,等等。

  2. Making a grid that the player could reference its movement to.制作一个玩家可以参考其移动的网格。

You will benefit more on making a grid first, and snapping your character to those grids.首先制作一个网格,然后将您的角色捕捉到这些网格,您将受益更多。 This way, you could restrict the character to follow the uniformed grid that you made with ease, and also use the grid for AI or NPC where they can do pathfinding.这样,您可以限制角色遵循您轻松制作的统一网格,也可以将网格用于 AI 或 NPC,他们可以在其中进行寻路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM