- Home /
Best way to rotate child and parent game objects in different axes without the rotation going crazy or glitchy?
I'm new and I'm still not sure how rotations work. I know the solution to my problem probably has to do with localRotation, but I'm lost.
What I want to do is to make an object that rotates in its own X axis based on the mouse X, while inside a parent that rotates in its own Y axis, based on the mouse Y. All of that inside a box rigidbody that is free to rotate in all kinds of ways, with all the rotations "adding" (that is, not ignoring the parent's rotation). Would also be good to clamp the child's X at 90°/-90° and its parent's Y at 180°/-180°.
If it helps, this is a solution I came up with for my camera, since I noticed the scripts sometimes do some weird rotations. I started thinking mechanically and how a robot would do it, as well as how our necks do it, and that was the solution I came up with. So, naturally, if there is a better or simpler way of getting this desired mechanical first person effect, that would be great.
Any help is massively appreciated.
Answer by UnderAbsoluteZero · Jul 26, 2018 at 03:21 PM
Ok after some trial and error, I ended up using Input.GetAxis and transform.Rotate with the technique I described. Looking around works as intended (works wonderfully if I do say so myself, I'm surprised with how well that worked) but I couldn't figure out how to clamp the rotation.
The code ended up being the simplest camera code I've seen, two scripts in two objects:
The parent:
void Update()
{
transform.Rotate(0, (Input.GetAxis("Mouse X")) * Time.deltaTime * 500, 0);
}
The child:
void Update()
{
transform.Rotate(-(Input.GetAxis("Mouse Y")) * Time.deltaTime * 500, 0, 0);
}