提问人:Krellex 提问时间:2/25/2022 最后编辑:Krellex 更新时间:2/25/2022 访问量:69
OnDrawGizmos 未在生成的网格中绘制所有网格位置
OnDrawGizmos not drawing all Grid positions in generated Grid
问:
我有一个正在生成的网格来执行路径查找。在存储所有可行走的节点时,我执行检查 HashSet 是否放置了障碍物。我正在将 a 传递给函数,但我认为无法识别传入的 Node。Obstacles
Node
IsCellOccupied(Node node)
.Contains
帕斯特宾网格.cs
Node 类继承 但是,使用此和实现方法会产生 Grid 的奇怪结果,其中可以找到许多空白点。只有在放置红色障碍物的地方,该区域才应该是空的,而不是绿色的。IEquatable
public bool Equals(Node other)
删除继承及其方法将生成完整的 Grid。然而,即使在障碍物下,整个网格现在也会被生成,它应该是空的IEquatable
我似乎无法弄清楚哪里出了问题。我认为这与函数执行的检查有关,但我不确定我错过了什么。.Contains
IsCellOccupied
节点
public class Node : IEquatable<Node>
{
public Vector3 Position { get; set; }
public CellType CellType { get; set; }
public int Cost { get; set; }
public Node parentNode {get; set;}
public Node(Vector3 position, CellType cellType, int cost)
{
Position = position;
CellType = cellType;
Cost = cost;
}
public override int GetHashCode()
{
return Position.GetHashCode();
}
public bool Equals(Node other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return GetHashCode() == other.GetHashCode();
}
public override bool Equals(object obj)
{
if((obj == null) || ! this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
Node n = (Node)obj;
return Position == n.Position;
}
}
}
IsCellOccupied 函数
private bool IsCellOccupied(Node node)
{
if (Obstacles.Contains(node))
return true;
return false;
}
实施建议的更改
建议将 y 设置为 0。这似乎仍然在障碍物所在的位置放置了一个绿色节点。
public override int GetHashCode()
{
return new Vector3(Position.x, 0, Position.y).GetHashCode();
}
答:
0赞
ATM
2/25/2022
#1
尝试以网格方式实例化障碍物,将要实例化的对象被修改为障碍物,而不是通过脚本制作整个障碍物
1赞
hijinxbassist
2/25/2022
#2
可以在 Grid.cs 的 PlaceObject 函数中找到该问题
var cellPosition = new Node(new Vector3(positionX, 0, positionZ), CellType.Land, 1);
...
var objectPosition = cellPosition; // <- objectPosition references the same object!
objectPosition.Position = new Vector3(
objectPosition.Position.x,
ObstaclePrefab.transform.position.y, // <- you are altering the y component here
objectPosition.Position.z
);
这确实是有道理的,直到你开始实施。GetHashCode()
return Position.GetHashCode();
向量的 y 分量不再为零,它基于您的障碍物。因此,现在如果您尝试比较 y=0 的新节点,则不会有匹配项(除非障碍物 y 分量为零)。
if (!IsCellOccupied(new Node(new Vector3(x, 0, z), CellType.Land, 1)))
我们可以通过几个调试在统一中对此进行测试。
var v1 = new Vector3(3, 0, 3);
var v2 = new Vector3(3, 1, 3);
Debug.Log($"V1) {v1.GetHashCode()}");
Debug.Log($"V2) {v2.GetHashCode()}");
// Outputs:
// V1) 1347420160
// V2) -1370488832
解决方案
忽略函数中的 y 分量。Position
GetHashCode()
public override int GetHashCode()
{
return new Vector3(Position.x, 0, Position.y).GetHashCode();
}
评论
0赞
Krellex
2/25/2022
感谢您的回复!我已经按照您的建议实施了更改,但它似乎仍然没有忽略放置障碍物的位置,而只是在那里添加了一个绿色节点。我将更新帖子以显示输出。
0赞
hijinxbassist
2/27/2022
看起来还有另一个地方可以直接比较位置,在 Node 的 Equals 函数中。 尝试将其更改为使用 GetHashCode()。return Position == n.Position;
评论