Question by
matus-kacmar · Mar 30, 2018 at 06:07 PM ·
cameracamera-movementcamera rotate
FPS camera rotating uncontrollably
Hello. I'm learning unity and I have a problem with making FPS style camera movement. For some reason when I move mouse just slightly it starts to rotate uncontrollably. This script is attached to Player game object which is a classic capsule and it has MainCamera as a child. All camera movement handling happens in cameraMovement method. transform.localEulerAngles is rotation of player game object and playerCamera.transform.localEulerAngles is rotation of camera it self. I'm doing x and y rotation separately to achieve player movement in direction where camera is facing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private CharacterController controller;
private Camera playerCamera;
private Vector3 playerDirection, cameraRotationX, cameraRotationY;
private float gravity = 9.81f;
private float xCameraAxis, yCameraAxis;
[SerializeField]
private float mouseSensitivity, movementSpeed;
// Use this for initialization
void Start () {
controller = GetComponent<CharacterController>();
playerCamera = this.GetComponentInChildren<Camera>();
}
// Update is called once per frame
void FixedUpdate () {
cameraMovement();
playerMovement();
}
void cameraMovement() {
cameraRotationX = playerCamera.transform.localEulerAngles;
xCameraAxis = cameraRotationX.x + (Input.GetAxisRaw("Mouse Y") * mouseSensitivity * Time.deltaTime);
cameraRotationX.x += xCameraAxis;
playerCamera.transform.localEulerAngles = cameraRotationX;
cameraRotationY = transform.localEulerAngles;
yCameraAxis = cameraRotationY.y + (Input.GetAxisRaw("Mouse X") * mouseSensitivity * Time.deltaTime);
cameraRotationY.y += yCameraAxis;
transform.localEulerAngles = cameraRotationY;
}
void playerMovement() {
playerDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
playerDirection.y -= gravity;
playerDirection = transform.transform.TransformDirection(playerDirection);
controller.Move(playerDirection * movementSpeed * Time.deltaTime);
}
}
Comment