Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question help with third person player rotation

Discussion in 'Getting Started' started by ducklanks, Jun 3, 2023.

  1. ducklanks

    ducklanks

    Joined:
    Jan 23, 2022
    Posts:
    10
    i followed a brackeys video on how to do third person movement I did exactly what it said but when I try and move the camera spins around while moving

    this is my code
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Thirdpersonmovement : MonoBehaviour
    6. {
    7.     public CharacterController controller;
    8.  
    9.     public Transform cam;
    10.  
    11.     public float speed = 6f;
    12.  
    13.     public float turnSmoothTime = 0.1f;
    14.     float turnSmoothVelocity;
    15.  
    16.     private void Start()
    17.     {
    18.         Cursor.lockState = CursorLockMode.Locked;
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.         float horizontal = Input.GetAxisRaw("Horizontal");
    25.         float vertical = Input.GetAxisRaw("Vertical");
    26.         Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
    27.  
    28.         if(direction.magnitude >= 0.1f)
    29.         {
    30.             float targetangle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
    31.             float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetangle, ref turnSmoothVelocity, turnSmoothTime);
    32.             transform.rotation = Quaternion.Euler(0f, angle, 0f);
    33.  
    34.             Vector3 moveDir = Quaternion.Euler(0f, targetangle, 0f) * Vector3.forward;
    35.             controller.Move(moveDir * speed * Time.deltaTime);
    36.         }
    37.     }
    38. }
    39.