Search Unity

Problem with camera script

Discussion in 'Scripting' started by Visama, Nov 16, 2019.

  1. Visama

    Visama

    Joined:
    Jun 27, 2019
    Posts:
    4
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraController : MonoBehaviour
    6. {
    7.     private GameObject player;
    8.  
    9.     private float speedH = 2.0f;
    10.     private float speedV = 2.0f;
    11.     private float yaw = 0.0f;
    12.     private float pitch = 0.0f;
    13.  
    14.     private void Awake() {
    15.         Cursor.lockState = CursorLockMode.Locked;
    16.         player = transform.parent.gameObject;
    17.     }
    18.  
    19.     private void Update() {
    20.         Cursoru();
    21.     }
    22.  
    23.     private void Cursoru() {
    24.         yaw += speedH * Input.GetAxis("Mouse X");
    25.         pitch -= speedV * Input.GetAxis("Mouse Y");
    26.  
    27.         transform.eulerAngles = new Vector3(Mathf.Clamp(pitch, -45f, 45f);, yaw, 0.0f);
    28.  
    29.         player.transform.eulerAngles = new Vector3(0.0f, yaw, 0.0f);
    30.     }
    31. }
    When I run the code I can rotate the camera correctly and so on. But if I keep moving the mouse up or down, and then I want to look in the opposite direction, I have to move it a lot so it actually rotates the camera. I don't get any error in console so I don't know what I can do to solve that bug.
     
  2. Visama

    Visama

    Joined:
    Jun 27, 2019
    Posts:
    4
    Nevermind, I've just fixed it :D I tried to do this once but it didn't look like it worked. Now it worked
    I just added this code
    pitch = Mathf.Clamp(pitch, -45f, 45f);
    over the line that says
    transform.eulerAngles = new Vector3(Mathf.Clamp(pitch, -45f, 45f), yaw, 0.0f);
    and then replace the Mathf.Clamp() on the new Vector3() with the variable.