首页 > 解决方案 > 如何在 4 方向 2D 游戏中实现基于网格的运动?

问题描述

我正在开发一个 4 方向(上、下、左、右)的 2D 游戏,它将使用基于网格的运动,但我无法弄清楚如何解决它。

公共类播放器:字符{

/// <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;
    }

}

标签: c#grid2d

解决方案


你可以通过两种方式做到这一点:

  1. 您可以在 x 和 y 属性上添加一个值,并确保它们没有浮动数字。即:x + 1 向右走,x - 1 向左走,等等。

  2. 制作一个玩家可以参考其移动的网格。

首先制作一个网格,然后将您的角色捕捉到这些网格,您将受益更多。这样,您可以限制角色遵循您轻松制作的统一网格,也可以将网格用于 AI 或 NPC,他们可以在其中进行寻路。


推荐阅读