- Home /
 
 
               Question by 
               ResigningNormal · Aug 28, 2021 at 10:01 AM · 
                camerarotationcollisioncamera rotate  
              
 
              Camera rotates when I run into a wall
Hello, I am new to unity and when I walk into a wall in my 1st person game, the camera starts to rotate. This is my code for the player movement.
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 [RequireComponent(typeof(Rigidbody))]
 public class PlayerMovement : MonoBehaviour
 {
     [SerializeField] private Rigidbody rigidbodyComponent;
     float movementSpeed = 5.0f;
     float sprintBonus = 2.0f;
 
     // Start is called before the first frame update
     void Start()
     {
         rigidbodyComponent = GetComponent<Rigidbody>();
     }
 
     // Update is called once per frame
     void Update()
     {
         if (Input.GetKey(KeyCode.W))
         {
             transform.position += transform.forward * Time.deltaTime * movementSpeed;
         }
         else if (Input.GetKey(KeyCode.S))
         {
             transform.position -= transform.forward * Time.deltaTime * movementSpeed;
         }
         if (Input.GetKey(KeyCode.A))
         {
             transform.position -= transform.right * Time.deltaTime * movementSpeed;
         }
 
         if (Input.GetKey(KeyCode.D))
         {
             transform.position += transform.right * Time.deltaTime * movementSpeed;
         }
 
         if (Input.GetKeyDown(KeyCode.LeftShift))
         {
             movementSpeed += sprintBonus;
         } 
 
         if (Input.GetKeyUp(KeyCode.LeftShift))
         {
             movementSpeed -= sprintBonus;
         }
     }
 }
 
               And this is the code for the camera in case that is the problem.
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class CameraFollowMouse : MonoBehaviour
 {
     public Transform playerBody;
     public float mouseSensitivity = 500f;
 
     float xRotation = 0f;
 
     void Start()
     {
         Cursor.lockState = CursorLockMode.Locked;
     }
 
     void Update()
     {
         float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
         float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
 
         xRotation -= mouseY;
         xRotation = Mathf.Clamp(xRotation, -90f, 50f);
 
         transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
         playerBody.Rotate(Vector3.up * mouseX);
     }
 }
 
              
               Comment
              
 
               
              Your answer