- Home /
Finding the center of several GameObjects
Hi, I'm trying to find the average center of several gameObjects. Here's my script thus far:
Transform[] transforms = model.gameObject.GetComponentsInChildren<Transform>();
Vector3 center = new Vector3(0,0,0);
int childCount = 0;
foreach(Transform tfs in transforms) {
center+=tfs.position;
childCount++;
}
center /= childCount;
Vector3 velocity = Vector3.zero;
target.transform.position = Vector3.SmoothDamp(target.transform.position, center, ref velocity, smoothTime);
It all seems reasonable to me. However, target's transform ends up being far from what I can visually attest as to being the center. If there's only one gameObject as a child of "model", it should center on that gameObject only correct? It doesn't. Therefore, I've concluded that the logic behind this script is flawed somewhere.
If somebody could point out that flaw, I'd be grateful.
Thanks, Elliot Bonneville
Answer by DaveA · Feb 07, 2011 at 10:48 PM
It's going to get all the children AND the their container (model). So if you have one child, it will average that child with 'model'.
You might
for (var child : Transform in transform)
which (the docs imply) do not contain that containing object.
You might also try to accumulate localPosition instead, and get world coords by adding 'model's position, but should not be needed I think.
Your answer
Follow this Question
Related Questions
SphereCast casts from the circumference, not the center of the sphere 1 Answer
Instantiated Game Object is at the wrong location. 1 Answer
Why the guismo of the GameObject is at the center but its "mesh" is not at all in the center? 0 Answers
How to get the center point of an object without any renderers? 2 Answers
Move from center and not pivot. 1 Answer