0

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); } 
1
  • Going by the code above you haven't set nearRadius to be anything, you've just created it as a Vector2. Surely it needs some information regarding distance, etc? Commented Mar 13, 2019 at 20:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To be exact how the OP had it the playerLayer value was used for the angle parameter (implicitly typecasted to float) and the default DefaultRaycastLayers as layerMask
@derHugo, exactly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.