Quackyrole
Quackyrole

Reputation: 1

Physics2D.OverlapBox always returning true

I'm coding a system to check if a player is in a certain area next to the enemy. I decided to use Physics2D.OverlapBox, but when I test it, no matter what, it always returns true.

Here's the code:

public bool isNear = false;

private Vector2 nearRadius;

public float nearRadiusLength;

public LayerMask playerLayer;

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

Upvotes: 0

Views: 1712

Answers (1)

Fay
Fay

Reputation: 122

As stated by Steve in the comment, you're using the variable nearRadius in your function, but it's a private variable and its value is not being set. Try to make it public and set its value in the inspector.

Also take a look at the Physics2D.OverlapBox documentation, the parameter angle seems not optional.

For instance you can set the angle to 0 in the method call:

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

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

And last but not least, make sure the layer from the game object which is holding the script is not marked in the defined layer mask playerLayer, otherwise the Physics2D.OverlapBox will detect the collision with it too.

Upvotes: 1

Related Questions