- Home /
Get a gameobject position relative to another?
How would I get the position of one gameobject relative to another (where the axis align)? Thanks!
Answer by aldonaletto · May 21, 2012 at 03:41 AM
Question too vague! Anyway, you can use something like this:
var obj1: GameObject; // drag the objects to these fields in the Inspector var obj2: GameObject;
function Start(){ var relativePos = obj1.transform.position - obj2.transform.position; print("relative position: "+relativePos.ToString()); } NOTE: When an object is childed to another, its transform.localPosition holds exactly the position relative to its parent in the parent's local space: if the child is 1 unit ahead of the parent, for instance, its transform.localPosition will be (0,0,1), no matter which's the parent rotation. In some cases it's better to child the object to some parent and use its localPosition.
my apologies, for example I have two objects and I want the Vector3 of one object relative to the other so that their axis align. I guess its like parenting, but I don't want to actually have to parent first. Hope this clarifies it a bit.
Not clear enough...
If you want to keep obj2 in the same Z coordinate as obj1, for instance, you can just copy the desired coordinate:
function Update(){
obj2.transform.position.z = obj1.transform.position.z;
}
This will keep both objects at the same plane perpendicular to Z.
But if you want to align the axes of two objects, you can copy transform.rotation, like this:
function Update(){
obj2.transform.rotation = obj1.transform.rotation;
}
sorry I'm not so good at explaining things. But I think .InverseTransformPoint is what I wanted to use. Thank you for working with me on this!
Ok, it's the relative position in local space - the same as localPosition, but without the parent link, as you've tried to explain.