【问题标题】:Physics2D.OverlapBox always returning truePhysics2D.OverlapBox 总是返回真
【发布时间】:2019-03-13 20:15:25
【问题描述】:

我正在编写一个系统来检查玩家是否在敌人旁边的某个区域。我决定使用Physics2D.OverlapBox,但是当我测试它时,无论如何,它总是返回true。

代码如下:

public bool isNear = false;

private Vector2 nearRadius;

public float nearRadiusLength;

public LayerMask playerLayer;

void FixedUpdate()
{
    isNear = Physics2D.OverlapBox(transform.position, nearRadius,playerLayer);
}

【问题讨论】:

  • 按照上面的代码,您没有将 nearRadius 设置为任何值,您只是将其创建为 Vector2。当然它需要一些关于距离等的信息?

标签: c# unity3d game-physics


【解决方案1】:

正如史蒂夫在评论中所说,您在函数中使用了变量 nearRadius,但它是一个私有变量,它的值没有被设置。尝试将其设为 public 并在检查器中设置其值。

另外看看Physics2D.OverlapBox文档,angle这个参数好像不是可选的。

例如,您可以在方法调用中将角度设置为 0:

public bool isNear = false;
public Vector2 nearRadius;
public LayerMask playerLayer;

void FixedUpdate()
{
    isNear = Physics2D.OverlapBox(transform.position, nearRadius, 0f, playerLayer);
}

最后但同样重要的是,确保游戏对象中包含脚本的图层在定义的图层蒙版playerLayer 中标记,否则Physics2D.OverlapBox 将检测到碰撞也有。

【讨论】:

  • 确切地说,OP 如何将playerLayer 值用于angle 参数(隐式类型转换为浮点数),默认DefaultRaycastLayerslayerMask
  • @derHugo,没错!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
相关资源
最近更新 更多