Search Unity

Question Restrict player x axis rotation

Discussion in 'Scripting' started by Spitfir3U, Dec 4, 2022.

  1. Spitfir3U

    Spitfir3U

    Joined:
    Dec 3, 2022
    Posts:
    1
    Hi i am trying to restrict the players x axis and cannot seem to figure out a solution with my code, clamping does not work at all. Any assistance would be appreciated.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using Unity.VisualScripting;
    4. using UnityEditor.Experimental.GraphView;
    5. using UnityEngine;
    6.  
    7. public class CharController : MonoBehaviour
    8. {
    9.     public float speed = 3.0F;
    10.  
    11.     public float rotationSpeed = 4.0f;
    12.     private float Pitch = 0.0f;
    13.     private float Yaw = 0.0f;
    14.  
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.         CharacterController controller = GetComponent<CharacterController>();
    19.  
    20.         // Disable Cursor Visibility and lock it to centre of screen
    21.         Cursor.visible = false;
    22.         Cursor.lockState = CursorLockMode.Locked;
    23.     }
    24.  
    25.     // Update is called once per frame
    26.     void Update()
    27.     {
    28.         // Get the Character controller
    29.         CharacterController controller = GetComponent<CharacterController>();
    30.  
    31.         // Move forward / backward
    32.         Vector3 forward = transform.TransformDirection(Vector3.forward);
    33.         float curSpeed = speed * Input.GetAxis("Vertical");
    34.         controller.SimpleMove(forward * curSpeed);
    35.  
    36.         // Set Pitch and Yaw with mouse
    37.         Yaw = Input.GetAxis("Mouse X") * rotationSpeed;
    38.         Pitch = Input.GetAxis("Mouse Y") - Input.GetAxis("Mouse Y") * rotationSpeed;
    39.  
    40.         Pitch = Mathf.Clamp(Pitch, -80, 80);
    41.  
    42.         // Apply Pitch and Yaw to player
    43.         transform.eulerAngles += new Vector3(Pitch, Yaw, 0);
    44.  
    45.     }
    46. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,744