在 Unity C# 中将 layerMasks 与 Physic2D.Linecast() 一起使用
Using layerMasks with Physic2D.Linecast() in Unity C#
我有一个简单的 DirectPath bool 函数,它根据两点之间是否有墙来 return 真或假。
public bool DirectPath (Vector2 start, Vector2 end) {
RaycastHit2D hitWall = Physics2D.Linecast (start, end, 8);
if (hitWall == null) {
Debug.Log ("Direct path returning true");
return true;
} else {
Debug.Log ("Direct path returning false");
return false;
}
}
我已将游戏中所有墙壁碰撞器的 layerMask 设置为 "Wall",这是我图层列表中的第 8 位。但是函数每次都是 returning false,这意味着每次都在撞墙。 "start" 点也不在对撞机内部,所以它不可能撞到自己的对撞机。但是我想使用这个相同的函数来确定玩家的视线,所以这将涉及一个碰撞器。
您的问题在这一行:
RaycastHit2D hitWall = Physics2D.Linecast (start, end, 8);
应该是这样的:
RaycastHit2D hitWall = Physics2D.Linecast (start, end, (1<<8));
为什么?因为该参数需要层 mask,即层的位掩码,而不是索引。
该参数不只需要一层,它提供了根据掩码中位的顺序定义的针对多个层进行投射的选项(所有位都将为 0,除了您设置为 1 的位)。这允许您组合蒙版,并执行 ~(1<<8)
之类的操作,它针对除 8.
之外的所有层进行投射
相关文档:https://docs.unity3d.com/Manual/Layers.html
编辑:
另一个问题是 RaycastHit2D 是结构类型。这意味着它将永远不为空。
您想检查if (hitWall.collider == null) {
参见:http://answers.unity3d.com/questions/691622/why-does-raycast2d-always-return-non-null.html
我有一个简单的 DirectPath bool 函数,它根据两点之间是否有墙来 return 真或假。
public bool DirectPath (Vector2 start, Vector2 end) {
RaycastHit2D hitWall = Physics2D.Linecast (start, end, 8);
if (hitWall == null) {
Debug.Log ("Direct path returning true");
return true;
} else {
Debug.Log ("Direct path returning false");
return false;
}
}
我已将游戏中所有墙壁碰撞器的 layerMask 设置为 "Wall",这是我图层列表中的第 8 位。但是函数每次都是 returning false,这意味着每次都在撞墙。 "start" 点也不在对撞机内部,所以它不可能撞到自己的对撞机。但是我想使用这个相同的函数来确定玩家的视线,所以这将涉及一个碰撞器。
您的问题在这一行:
RaycastHit2D hitWall = Physics2D.Linecast (start, end, 8);
应该是这样的:
RaycastHit2D hitWall = Physics2D.Linecast (start, end, (1<<8));
为什么?因为该参数需要层 mask,即层的位掩码,而不是索引。
该参数不只需要一层,它提供了根据掩码中位的顺序定义的针对多个层进行投射的选项(所有位都将为 0,除了您设置为 1 的位)。这允许您组合蒙版,并执行 ~(1<<8)
之类的操作,它针对除 8.
相关文档:https://docs.unity3d.com/Manual/Layers.html
编辑:
另一个问题是 RaycastHit2D 是结构类型。这意味着它将永远不为空。
您想检查if (hitWall.collider == null) {
参见:http://answers.unity3d.com/questions/691622/why-does-raycast2d-always-return-non-null.html