在Unity

时间:2018-01-21 11:28:48

标签: c# arrays unity3d

我可以为我的播放器设置四种不同的移动方向

  • Vector2.up => (0,1)
  • Vector2.down => (0,-1)
  • Vector2.left => (-1,0)
  • Vector2.right => (1,0)

我有一个包含Cell个对象的二维数组

public class Cell
{
    public Cell(GameObject cellObject, bool isObstacle)
    {
        CellObject = cellObject;
        IsObstacle = isObstacle;
    }

    public GameObject CellObject { get; set; }

    public bool IsObstacle { get; set; }
}

我的数组是根据地图的大小初始化的。

private const int MAP_SIZE = 10;
private Cell[,] mapCells = new Cell[MAP_SIZE, MAP_SIZE];

我使用两个循环填充此数组,这将给我100个单元格。

for (int x = 0; x < MAP_SIZE; x++)
{
    for (int y = 0; y < MAP_SIZE; y++)
    {
        Vector3 newCellPosition = new Vector3(x, 0, y);
        GameObject newCellObject = Instantiate(cell, newCellPosition, cell.transform.rotation);

        bool isObstacle = false; // TEST

        Cell newCell = new Cell(newCellObject, isObstacle);
        mapCells[x, y] = newCell;
    }
}

当移动玩家时,我想要返回他必须移动的Cell。 movementDirection参数将设置要搜索的行和列。

如果有障碍物,则玩家应该移动到此障碍物并停止。

Path

public Cell GetTargetCell(Vector2 movementDirection)
{
    Cell targetCell = null;

    // get the path

    // get the closest obstacle

    return targetCell;
}

是否有一种优雅的方法可以通过2D方向计算正确的目标单元格?

1 个答案:

答案 0 :(得分:1)

我认为最优雅的方法是使用两个单独的for循环和?: operator

//returns cell
Cell GetTargetCell(Vector2 dir)
{
    if(dir.y == 0) //if we're going horizontal
    {
        //HorizontalMovement
        for(int i = 0; i < ((dir.x==1)?mapSize-PLAYER_X:PLAYER_X); i++)
        {
            if(mapCells[(int)dir.x*i,PLAYER_Y].IsObstacle()) //if we encounter an obstacle
                return mapCells[(int)dir.x*i,PLAYER_Y]; //return cell that's an obstacle
        }

        //if we didn't encounter an obstacle
        return mapCells[(dir.x == 1)?mapSize:0,PLAYER_Y]; //return the cell
    }
    else if(dir.x == 0)
    {
        //VerticalMovement
        //copy paste the previous for loop and edit the parameters, I'm too lazy :P
    }
    else
    {
        //NoMovement
        Debug.Log("Please enter a valid Direction");
        return mapCells[0,0];
    }


}

将PLAYER_X和PLAYER_Y值替换为播放器当前所在单元格的x和y值。我没有检查代码是否包含任何错误,但我认为它应该有效。