How to find the center of a Box Collider 2D?

Hi!

I want to instantiate an object exactly in center of a Box Collider but I don’t know what should write in the position part of the Instantiate function that is a Vector3

Instantiate(prefab , position , rotation);

Than you for help!

4 Answers

4

Apply the Box Collider’s center xyz offsets to the gameObject’s position:

Vector3 g_position = gameObject.transform.position;
BoxCollider box = GetComponent("BoxCollider");
  
Vector3 box_center = g_position + box.center;

You forgot about the GameObject scaling and rotation

Extension methods to not repeat the arithmetic all the time:

using UnityEngine;

public static class BoxCollider2DExtensions {
    public static Vector2 GetCenterAbs(this BoxCollider2D BoxCollider2D) {
        return (Vector2)BoxCollider2D.transform.position + BoxCollider2D.offset;
    }

    public static Vector2 GetCenterLocal(this BoxCollider2D BoxCollider2D) {
        return (Vector2)BoxCollider2D.transform.localPosition + BoxCollider2D.offset;
    }
}

Usage:


BoxCollider2D.GetCenterAbs();
BoxCollider2D.GetCenterLocal();

For BoxCollider: GetComponent<BoxCollider>().bounds.center
For BoxCollider2D: GetComponent<BoxCollider2D>().bounds.center

Please don't necropost. Also note, your answer is incorrect. The OP was asking about BoxCollider2D and you simply repeated what a dev posted in 2013.

The OP asked in the question about BoxCollider, but mentioned BoxCollider2D in the question title. Also, I didn't repeat what jogo13 posted in 2013. Additionally, I didn't necropost because there was no correct solution before I posted.

Since the question was already bumped and still doesn’t really have the correct answer, here are the two solutions for the two cases (2D and 3D)

BoxCollider2D box;
Vector2 center = box.transform.TransformPoint(box.offset);

BoxCollider box;
Vector3 center = box.transform.TransformPoint(box.center);

You can use the center of the boundingbox, but that’s quite a bit of overhead to calculate the whole bounds for the collider.

[quote="Bunny83, post:5, topic:60175"] You can use the center of the boundingbox, but that’s quite a bit of overhead to calculate the whole bounds for the collider. [/quote] Are you sure? The physics systems probably need to have the bounds at hand for a lot of things. It might be cached instead of being calculated on-demand, in which case fetching the bound's center would be faster than calculating the offset. I also think box.bounds.center is clearer than the TransformPoint call.