Physics2D Boxcast - can I get an example of correct usage?

Currently trying to use a Physics2D.Boxcast to return an array of touched items, as seen here: My code is as follows:

RaycastHit2D[] bashables = new RaycastHit2D[20];
            ContactFilter2D filter2D = new ContactFilter2D().NoFilter();
            if (Physics2D.BoxCast(halfHeight, box2D.size, 0.0f, raycastDirection, filter2D, out bashables, rayLength));

I can't seem to get the parameters to line up right for the version of the function I'm looking for. Can anybody here provide an example of the correct parameters?

Resolved, my problem was that I was placing the Boxcast in an if statement, where it doesn't return a bool.

Some observations though that might help:

  • It returns the number of hits so you can do "if (Physics2D.BoxCast(...) > 0)".
  • You're using "halfHeight" which seems to suggest a size but this is a position in the world.
  • You're passing in a fixed-array which limits you to 20 hits. I would suggest using the "List" overload which can return everything and the size of the list is also the number of hits returned. It'll automatically increase its capacity if needed. All 2D physics queries have this overload.
  • If you have an existing 2D collider then you can use Collider2D.Cast so you don't have to pass in its details.
1 Like

Thank you, that's very kind. Collider2D.Cast is particularly helpful!