- Home /
Lock an axis from rotating
I have a CharacterController that is rotating to always face where the camera is pointing but I want to lock an axis so that it wont lean back and forth when you look up and down.
void Update() {
CharacterController controller = GetComponent<CharacterController>();
Camera cam = GameObject.Find("CharCam").GetComponent<Camera>();
if (controller.isGrounded) {
currentSpeedX = Input.GetAxis("Horizontal");
currentSpeedZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(currentSpeedX, 0f, currentSpeedZ);
moveDirection = cam.transform.TransformDirection(moveDirection);
transform.rotation = cam.transform.rotation;
moveDirection *= speed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
Answer by Drakmyth · Dec 30, 2012 at 08:30 PM
I would just set the rotation values for the other two axes to be zero. Right before your transform.rotation line I would say
Vector3 rotVals = new Vector3(0, cam.transform.rotation.y, 0);
Then set transform.rotation to rotVals. Note that this assumes your controller works like the default FPS controller, which is that the camera itself never rotates left/right, only up/down. Left/right rotation is handled by actually rotating the entire controller (instead of just the camera). If you are actually rotating the camera left/right as well, this obviously won't work and I would recommend using an entirely Quaternion-based rotation system instead.
Your answer
Follow this Question
Related Questions
Rotate according to the camera on Y and Z only! 2 Answers
How to rotate an object on one axis facing another object? 0 Answers
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