Search Unity

BoxCollider2D, problem with corner

Discussion in '2D' started by FeboGamedeveloper, Sep 1, 2019.

  1. FeboGamedeveloper

    FeboGamedeveloper

    Joined:
    Feb 2, 2014
    Posts:
    47
    Hi, I need help:

    In the picture you see a rotated boxCollider2D, I am interested in code to find the points (the vectors) equivalent to the position where the top-left and top-right points of the boxCollider are located. I'm not very good with quaternions and since the rectangle is rotated, I can't find these points. Thanks for the help.

     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,473
    Here's a simple example of how to do that. Add it to a GameObject that has a BoxCollider2D on it and it'll calculate and draw the points of the corners. The part you actually want is in the "Update" method which simply takes the collider offset and half-size extents for the box then calculates each corner point in local-space. With this you can then transforms those local-space points into world-space using the Transform.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. [ExecuteInEditMode]
    4. public class FindBoxCorners : MonoBehaviour
    5. {
    6.     BoxCollider2D m_BoxCollider;
    7.     Vector2[] m_BoxPoints = new Vector2[4];
    8.  
    9.     void Start()
    10.     {
    11.         m_BoxCollider = GetComponent<BoxCollider2D>();    
    12.     }
    13.  
    14.     void Update()
    15.     {    
    16.         var offset = m_BoxCollider.offset;
    17.         var halfSize = m_BoxCollider.size * 0.5f;
    18.  
    19.         m_BoxPoints[0] = transform.TransformPoint(offset - halfSize);
    20.         m_BoxPoints[1] = transform.TransformPoint(offset + new Vector2(halfSize.x, -halfSize.y));
    21.         m_BoxPoints[2] = transform.TransformPoint(offset + halfSize);
    22.         m_BoxPoints[3] = transform.TransformPoint(offset + new Vector2(-halfSize.x, halfSize.y));    
    23.     }
    24.  
    25.     private void OnDrawGizmosSelected()
    26.     {
    27.         var oldColor = Gizmos.color;
    28.         Gizmos.color = Color.cyan;
    29.  
    30.         for (var i = 0; i < m_BoxPoints.Length; ++i)
    31.             Gizmos.DrawSphere(m_BoxPoints[i], 0.1f);
    32.  
    33.         Gizmos.color = oldColor;
    34.     }
    35. }
    36.