- Home /
Camera follow
I want my mouse to be able to rotate the main camera around the player (up and down), but when I try to do it, it glitches and will not let me. I can do it horizontally, but not vertically . See this to understand my problem
- I have attached my main camera to my player object.
- There is no camera follow script.
- I want my camera to rotate around my player
- there is no rigid body, I am using a character controller
public class PlayerMovement : MonoBehaviour {
public float moveSpeed;
public Transform target;
public float jumpForce;
public CharacterController cc;
private Vector3 moveDirection;
public float gravityScale;
public float Xsensitivity;
public float Ysensitivity;
public Transform Pivot;
public Camera camera;
private Vector3 rotateValue;
void Start(){
camera = Camera.main;
camera.enabled = true;
cc = GetComponent<CharacterController>();
target.GetComponent<Transform>();
Pivot.transform.position = target.transform.position;
Pivot.transform.parent = target.transform;
Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate(){
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
float hor = Input.GetAxis("Mouse X") * Xsensitivity;
target.Rotate(0.0f, hor, 0.0f);
float vert = Input.GetAxis("Mouse Y") * Ysensitivity;
Pivot.Rotate(-vert, 0, 0);
rotateValue = new Vector3(hor, vert * -1, 0.0f);
camera.transform.eulerAngles = transform.eulerAngles - rotateValue;
float yStore = moveDirection.y;
moveDirection = (transform.forward * v) + (transform.right * h);
moveDirection = moveDirection.normalized * moveSpeed;
moveDirection.y = yStore;
if (cc.isGrounded){
moveDirection.y = 0.0f;
if (Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpForce;
}
}
moveDirection.y += (Physics.gravity.y*gravityScale*Time.deltaTime);
cc.Move(moveDirection*Time.deltaTime);
}
}
THank you in advance :)
Answer by iJuan · May 12, 2018 at 01:18 AM
First of all:
Inputs should never be on FixedUpdate
If you put inputs in FixedUpdate(), there's a chance you will miss some frames.
Said that, your camera should be at LateUpdate, so all changes on that frame will be reflected. Once that's done, your camera should work, but it will probably bug your CharacterController (The player should always me moved before the camera does)
I'd recommend you to manage player's Input in your Character controller and Camera's Input in a Camera Controller, don't try to mix them.
Your answer
