- Home /
Rotating parent and positioning child between parent and camera.
I have a parent/child object structure.
I'm positioning the child so it always sits on the vector between the parent and the camera.
The following code is attached to the child.
Vector3 diff = Camera.main.transform.position-this.gameObject.transform.parent.position;
Vector3 unitVector = Vector3.Normalize (diff);
this.transform.localPosition = (10f * unitVector);
If I rotate the parent, this child is no longer between the camera and the parent.
So, I thought all I'd need to do would be to rotate the unit Vector by the rotation applied the parent or, rotate the child back by this angle.
I was wrong.
I'm unsure as to why this wouldn't work?
Not sure how you are doing your 'back' angle. Given that you apply a Quaternion rotation of q to the parent, I believe (I'm away from my desk and cannot test) you can do:
unitVector = Quaternion.Inverse(q) * unitVector;
Answer by VesuvianPrime · Jul 29, 2014 at 12:28 AM
Hi Rickw
Firstly, an architecture nag: ideally a child should not be aware of it's parent. Have you considered moving this code into the parent?
I think the main problem with your code is you're overthinking things. Check this out:
Vector3 cameraPosition = Camera.main.transform.postion;
Vector3 midPoint = (transform.position + cameraPosition) / 2.0f;
myChild.transform.position = midPoint;
No need to worry about calculating distance or normalizing things. You just need to get the midpoint and set the WORLD position of the child.