- Home /
Aligning objects on their relative plane.
Hello, I need to align two objects using script. I have two objects, and I want to "connect" them so that if I rotate one, the other rotates, just as if were a child. The only thing is, I cannot actually parent either on of them, because they are rigidbodys that should perform independently. I essentially want to constrain two of their axis to one another.
I am actually making a shock absorber, so the top and bottom of the shock need to stay inline, but must allow for compression.
I know I can achieve this with the "Object Constraints", but I need it to be relative, not in world space, so if the shock rotates, the parts still work properly.
Hopefully that is understandable. Thank You
Answer by robertbu · Jul 12, 2013 at 03:03 PM
You are going to have to designate one as the parent and the other as the child. Then you will need to move and rotate the child to match the parent. I don't know what this will do the physics and specifically collision detection. To get them to align, I'd project the position of the child onto the line representing the axis of the parent I was aligning with. The Math3D script has a ProjectPointOnLine() function. Rotation you can handle in one of two ways. First, you can just match the rotation of the two objects. Or if you want to allow the child to spin on the axis, you can use a Quaternion.FromToRotation() rotation to match the axes. So if we use the 'up' vector of the parent for alignment (untested):
transform.position = ProjectPointOnLine(parentObj.position, parentObj.up, transform.position);
transform.rotation = parentObj.rotation;
Alternate rotation allowing child to spin on axis:
transform.rotation = Quaternion.FromToRotation(transform.up, parentObj.up) * transform.rotation;
Thank You, with some ideas from your answer, I got it sorted thanks.
Thanks! The second line was exactly what I needed to align an object with an artificial gravity source.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110000im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Constrain LookAt to Local Axis 2 Answers
Aligning to a specific axis (6 DOF Descent-like movement) 1 Answer
How can I align Axis? 0 Answers
Align an axis to a plane 0 Answers
How can I match/align two objects along 1 axis only? 2 Answers