【问题标题】:compare coordinate/directional objects比较坐标/方向对象
【发布时间】:2018-01-24 08:13:42
【问题描述】:

我有一个网格并获得了移动的方向。这个方向可以

  Vector2Int movementDirection = new Vector2Int(/* this can be
     (0,1) // up
     (0,-1) // down
     (-1,0) // left
     (1,0) // right
  */);

Vector2Int 是 Unity 框架中的一个类! https://docs.unity3d.com/ScriptReference/Vector2Int.html

从下到上移动时,我想检查 targetCell 周围的所有单元格。但我不想检查底部的单元格,因为这个单元格是我来自的地方。

当我从左向右移动时,我不想检查左边的单元格。

所以我选择了这个

private void CheckCells(Vector2Int movementDirection)
    {
        Vector2Int[] cellDirections = { Vector2Int.up, Vector2Int.down, Vector2Int.left, Vector2Int.right };
        cellDirections.Where(direction => !direction.Equals(movementDirection)).ToArray();

        for (int i = 0; i < cellDirections.Length; i++)
        {
            // check the other 3 cells
        }
    }

此数组的长度仍为 4。看来我无法将Vector2Int.up(0,1) 进行比较

我试过了

!direction.Equals(movementDirection)

directon != movementDirection

如何仅针对 4 个方向中的 3 个开始循环?给定的参数应该从数组中删除第四个方向。

也许我不需要数组?

【问题讨论】:

  • 您可能想尝试将equals 替换为== docs.unity3d.com/ScriptReference/Vector3.Equals.html
  • 通常,比较浮点数是用 epsilon 完成的。 (如果差值小于 epsilon,我们就认为它们是相等的)。这是因为它们不精确。您的移动方向可能偏离百万分之一,导致equals 表明它们不同。
  • 我更新了我的帖子,我现在使用Vector2Int

标签: c# unity3d


【解决方案1】:

这一行:

cellDirections.Where(direction => !direction.Equals(movementDirection)).ToArray();

对您的 cellDirections 变量没有任何作用,因为您没有分配结果。

要么尝试:

cellDirections = cellDirections
                 .Where(direction => !direction.Equals(movementDirection)).ToArray();

或任何其他任务:

var anyVar = cellDirections
             .Where(direction => !direction.Equals(movementDirection)).ToArray();

请注意,您也可以循环访问您的 cellDirections 并在您的 for 中添加一个 if

foreach (var direction in cellDirections)
{
    if(!direction.Equals(movementDirection))
    {
        // check the cells
    }
}

【讨论】:

  • 或者,更干净:foreach(var direction in cellDirections.Where(direction =&gt; !direction.Equals(movementDirection)) { /* check direction variable */ }
  • @TimothyGroote 我不知道在foreach 中使用Where 或添加if 哪个更干净,但你在这里有一点意义
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 2010-12-06
  • 2010-09-07
  • 1970-01-01
  • 2016-02-15
  • 2014-10-03
  • 1970-01-01
  • 2013-11-01
相关资源
最近更新 更多