- Home /
Rotate according to the camera on Y and Z only!
Hi guys, i have this code right now, that allows my character to have his rotation be relative to the camera when he moves, but the problem, is that i want it to be for the Y and Z axis only, so that, when the camera is a little up, the character dont incline to the ground, you know? Sorry for the bad english, i hope someone can help...
Transform mainCamera = Camera.main.transform; direction =new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")); rotation = Quaternion.LookRotation(direction, Vector3.up); transform.rotation = mainCamera.rotation * rotation;
This image here shows what is happening:
the character movement is exacltly like i want, it follows the camera rotations on y and z, but i want to lock the x rotation, so the character can stand still on the ground...
Answer by Owen-Reynolds · Oct 19, 2013 at 03:25 PM
Use a variant of the "cancel out y" LookAt trick. Set direction.y to 0 before getting the angle:
direction = new Vector3(Input.GetAxis("Horizontal")...);
direction.y = 0; // new. Direction is now "flat"
rotation = Quaternion.LookRotation(direction, Vector3.up);
This will give a bad quaternion error if the camera is ever pointed straight up or down (since direction will be 000,) but probably never happens and can be solved with an if.
Your answer
Follow this Question
Related Questions
Is there a way to lock my camera's rotation and movement on certain axis? 2 Answers
Camera rotating with physics based movement. 0 Answers
UI not rotating correctly when in "Canvas mode - Camera", I'm hard stuck on this 0 Answers
Mathf.Clamp is 'Sticky'? 1 Answer
Camera rotation around a single axis - following a rolling ball 3 Answers