Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Confused about BoxCasting distance

Discussion in '2D' started by Magnesium, Aug 3, 2021.

  1. Magnesium

    Magnesium

    Joined:
    Sep 14, 2014
    Posts:
    178
    Hello,

    I am trying to make a box-cast that would be quite thin and just stick out a little from my box collider, something looking like this:

    box-cast.png
    Here's my code:

    Code (CSharp):
    1. Vector3 center = _bodyCollider.bounds.center;
    2.     Vector2 size = new Vector2(0.05f, 0.63f);
    3.          
    4.     float distance =
    5.         (_bodyCollider.bounds.size.x / 2)
    6.         - (size.x / 2)
    7.         + Physics2D.defaultContactOffset + 0.1f;
    8.  
    9.     var hit = Physics2D.BoxCast(
    10.         center,
    11.         size,
    12.         0,
    13.         Vector2.right,
    14.         distance,
    15.         LayerMask.GetMask("Sols"));
    But the cast catches collisions way too far altough my calculation seems pretty alright to me, or at least with only a minor difference. I think i'm missing something about this distance. I tried a code found somewhere to visualize boxcasts but it didn't give accurate results.
     
  2. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    Are you maybe confusing BoxCast and BoxCollider/ BoxCollider2D?

    A BoxCast is like a RayCast but with an actually hitbox, as in, it does not only hit if the ray line goes through something but rather it hits if the projected box-ray hits something
    There are also a few more differences between BoxCast and RayCast but essentially, both look ahead to see if somewhere between the starting position and the max distance they have to go through another object

    if you just want to listen to colliders within your green rectangle from the first image, you want a BoxCollider2D not a BoxCast
     
    Magnesium likes this.
  3. Magnesium

    Magnesium

    Joined:
    Sep 14, 2014
    Posts:
    178
    Yes, you were right indeed, thank you very much!