Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Get Box Collider size and center according to child colliders

Discussion in 'Scripting' started by shahanbutt0, Sep 20, 2019.

  1. shahanbutt0

    shahanbutt0

    Joined:
    Apr 30, 2018
    Posts:
    2
    I have a parent gameobject which has multiple child gameobjects with box colliders.
    I want to make a box collider on my parent gameobject according to the child gameobject colliders.
    Meaning the new box collider should cover all the child colliders and its bounds should be on the corner of the child colliders as well.

    I have already gotten the size of my collider according to positions of my child colliders,
    I just cant calculate the center value of the collider.

    Here is my code till yet:
    Code (CSharp):
    1. public List<BoxCollider> childColliders = new List<BoxCollider>();
    2.  
    3.     public Vector2 maxXpos;
    4.     public Vector2 minXpos;
    5.     public Vector2 maxYpos;
    6.     public Vector2 minYpos;
    7.  
    8.     public float xDistance, yDistance;
    9.  
    10.     public void OnEnable()
    11.     {
    12.         xDistance = Vector3.Distance(maxXpos, minXpos);
    13.         yDistance = Vector3.Distance(maxYpos, minYpos);
    14.  
    15.         GetComponent<BoxCollider>().size = new Vector3(xDistance, yDistance, 5);
    16.     }
    17.  
    I have attached an image of what I am achieving right now.
     

    Attached Files:

    • SC1.PNG
      SC1.PNG
      File size:
      92.6 KB
      Views:
      49
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    837
    ((maxXpos + minXpos)/2f)-transform.position;
    Edited because i forgot things.
    Note that your logic probably would break if your child colliders are rotated in any way.
     
    Last edited: Sep 20, 2019
  3. shahanbutt0

    shahanbutt0

    Joined:
    Apr 30, 2018
    Posts:
    2
    What would be the proper way of doing then ?
     
  4. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    837
    You would need to get all the corners of the child colliders and calculate the min/max/bounds from all these points.
    But perhaps this is what you're doing already.