- Home /
How do i move an object relative to another objects axis.
Hi,
I got game object 1 that moves around. Game object 2 is supposed to always be 1 unit behind game object. In a script I need to set object 2's position 1 unit back relative to object 1's local axis, and not world space.
One way was to parent game object 2, however this is not always an option. I'm sure it's really simple, but I just can't wrap my brain around it right now. How do I do this?
Answer by ForbiddenSoul · Jan 10, 2016 at 10:55 PM
Well silly me try to figure this out for 2 hours, then ask the question and 2 seconds later, BAM! You figure it out. The answer was:
GameObject.transform.TransformDirection()
For anyone else wanting to do this
you have to set object 2's position = object 1's position (+/-) object 1's position.TransformDirection(the offset you want).
Something Like:
gameObject2.transform.position = gameObject1.position + gameObject1.TransformDirection(new Vector3(0, 1, -1));
If you wanted to add scale to this also (Confirmed that this does work on my end also), then you can add or subtract based on the world position(x,y,z direction), at the end of it the transforms localScale at that axis.
FOr example. If I made objA move right next to the edge of objB on the front of it, I would say,
gameObject2.transform.position = gameObject1.position + gameObject1.TransformDirection(new Vector3(0, 0, (gameObject1.localScale.z/2)) + or - gameObject2.transform.localScale.z/2));
Prob need to format it better with parethesis but the idea is to take into account scale of BOTH objects in relation to the direction formula. Hope that helps too for snapping objects and such that do not have a 1:1 ratio of each other.