【问题标题】:calculate grid path in Unity在 Unity 中计算网格路径
【发布时间】:2018-01-22 05:51:39
【问题描述】:

我有一个网格,可以为玩家设置四个不同的移动方向

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

我有一个包含Cell 对象的二维数组。 Cell 有一个布尔值 isObstacle 来检查玩家是否可以移动或必须停止。

private Cell[,] mapCells = new Cell[10, 10]; // the map is 10x10

填充数组时,我得到 100 个单元格。移动玩家时,我想检查他是否能够向特定方向移动。我通过一些 if 语句检查了这一点

  • 玩家没有在外面移动
  • 下一个单元格不是障碍物

我的代码

public Cell GetTargetCell(Vector2Int movementDirection) {
 Vector2Int targetCellIndex = new Vector2Int( /* currentPlayerPosX */ , /* currentPlayerPosY */ );

 while (targetCellIndex.x >= 0 &&
  targetCellIndex.y >= 0 &&
  targetCellIndex.x < mapCells.GetLength(0) &&
  targetCellIndex.y < mapCells.GetLength(1) &&
  !mapCells[targetCellIndex.x + movementDirection.x, targetCellIndex.y + movementDirection.y].IsObstacle) 
  {
  targetCellIndex += movementDirection;
  }

 return mapCells[targetCellIndex.x, targetCellIndex.y];
}

如您所见,我使用第五个 if 语句检查下一个单元格。唯一的问题是,如果 while 循环达到数组的最大索引并且我添加更高的索引,我将得到一个 IndexOutOfRangeException

!mapCells[nextX, nextY].IsObstacle // this might be out of range

有没有可能避免这个错误?

【问题讨论】:

    标签: c# arrays unity3d


    【解决方案1】:

    只需检查您的targetCellIndexmovementDirection 是否在界限内。您当前检查“旧坐标”是否已绑定,然后检查“新坐标”是否为IsObstacle。如果我的问题是正确的

    public Cell GetTargetCell(Vector2Int movementDirection) {
     Vector2Int targetCellIndex = new Vector2Int( /* currentPlayerPosX */ , /* currentPlayerPosY */ );
    
     while (targetCellIndex.x + movementDirection.x >= 0 &&
      targetCellIndex.y + movementDirection.y >= 0 &&
      targetCellIndex.x + movementDirection.x < mapCells.GetLength(0) &&
      targetCellIndex.y + movementDirection.y < mapCells.GetLength(1) &&
      !mapCells[targetCellIndex.x, targetCellIndex.y + movementDirection.y].IsObstacle) 
      {
      targetCellIndex += movementDirection;
      } else {
        //something wrong
        //do not move? to something else? your choice.
      }
    
    
     return mapCells[targetCellIndex.x, targetCellIndex.y];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多