- Home /
How to keep an object level to horizontal?
I'm modeling something like a camera jib, essentially, an articulated arm ends with a platform always level to horizontal. The platform has to rotate and move with the arm it's attached to, just remaining level.
This seems like it would be an easy problem, but nothing behaves the way I expect. I tried a script something like this:
void Update ()
{
//Get the world up vector in local coordinates.
Vector3 localUp = transform.InverseTransformDirection(Vector3.up);
//Get the angle we need to rotate to get local up vector aligned
//with world up vector.
float angle = Vector3.Angle(Vector3.up, localUp);
transform.Rotate(angle, 0, 0, Space.Self);
}
This does not work. In fact, what this does is make the platform spin around.
I've seen other people with a similar problem and it was recommended to do stuff like transform.up = Vector3.up
which also affects the other rotations, so the platform doesn't appear to be properly attached to the arm.
Surely somebody has solved this problem.
Answer by chronicfail · Jul 31, 2013 at 07:05 PM
it might work to add a kinematic rigidbody to the horizontal object and set the constraints to freexe the x and z rotations.
thanks. Don't know if I tried that. I did implemented a pendulum, which kind-of worked, but always swung too much.
Answer by HeywoodFloyd · Jul 31, 2013 at 07:28 PM
Solution is embarrassingly trivial:
void Update ()
{
Vector3 eulers = transform.eulerAngles;
eulers.x = 0;
transform.eulerAngles = eulers;
}