user-44651
user-44651

Reputation: 4124

Calculate total area height and width from various BoxCollider2Ds

I have a a BoxCollider2D on different child gameobjects that live in a single parent gameobject.

enter image description here

I need to know the total height and total width of the area of the box colliders.

During Start(), I loop through every child component, read the box collider size and add it to a Vector2 property called totalSize.

private Vector2 totalSize;

foreach (Transform child in transform)
{
    var col = child.GetComponent<BoxCollider2D>();
    if(col != null)
        totalSize += new Vector2(col.bounds.size.x, col.bounds.size.y);
}

However, this calculates ALL objects giving me 220 x 100 instead of giving me 100 x 50 for the pictured example. Where each grey box represents a BoxCollider2D.

How do I find the true area height and width given that each "box" can be different sizes or in a different configuration.

Upvotes: 3

Views: 334

Answers (1)

R Astra
R Astra

Reputation: 469

Try something like this. It should find the total size of the bounds of all the children together.

private Vector2 totalSize;

private float minX = Mathf.Infinity;
private float maxX = -Mathf.Infinity;
private float minY = Mathf.Infinity;
private float maxY = -Mathf.Infinity;

foreach (Transform child in transform)
{
    var col = child.GetComponent<BoxCollider2D>();
    if(col != null){
        if(col.bounds.max.x > maxX) maxX = col.bounds.max.x;
        if(col.bounds.min.x < minX) minX = col.bounds.min.x;

        if(col.bounds.max.y > maxY) maxY = col.bounds.max.y;
        if(col.bounds.min.y < minY) minY = col.bounds.min.y;
    }
}
totalSize = new Vector2(maxX-minX, maxY-minY);

Upvotes: 1

Related Questions