Search Unity

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

Discussion in '2D' started by Reverend-Speed, Mar 23, 2023.

  1. Reverend-Speed

    Reverend-Speed

    Joined:
    Mar 28, 2011
    Posts:
    284
    Currently trying to use a Physics2D.Boxcast to return an array of touched items, as seen here: https://docs.unity3d.com/ScriptReference/Physics2D.BoxCast.html My code is as follows:

    Code (CSharp):
    1. RaycastHit2D[] bashables = new RaycastHit2D[20];
    2.             ContactFilter2D filter2D = new ContactFilter2D().NoFilter();
    3.             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?
     
  2. Reverend-Speed

    Reverend-Speed

    Joined:
    Mar 28, 2011
    Posts:
    284
    Resolved, my problem was that I was placing the Boxcast in an if statement, where it doesn't return a bool.
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    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<RaycastHit2D>" 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.
     
  4. Reverend-Speed

    Reverend-Speed

    Joined:
    Mar 28, 2011
    Posts:
    284
    Thank you, that's very kind. Collider2D.Cast is particularly helpful!
     
    MelvMay likes this.