Search Unity

Smooth Turning & Moving Player Relative to Camera's Direction

Discussion in 'Animation' started by girlinorbit, Aug 6, 2019.

  1. girlinorbit

    girlinorbit

    Joined:
    Apr 27, 2019
    Posts:
    115
    So I have a player movement script that works well, I just want to widen the turning radius and make the direction the camera is facing forward. I've been researching this for some time and cannot come up with an answer. When the camera is facing forward, I want that direction to be forward. And when it turns, it want the new direction to be forward. I want the turning to be smoother to make it easier on the player when they change directions.

    I might also mention that I am new at C# but do have quite a bit of other programming experience.

    Here's my movement script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     public float turnSpeed = 20f;
    8.     public float distance = 5f;
    9.  
    10.     Animator m_Animator;
    11.     Rigidbody m_Rigidbody;
    12.     Vector3 m_Movement;
    13.     Quaternion m_Rotation = Quaternion.identity;
    14.  
    15.     void Start ()
    16.     {
    17.         m_Animator = GetComponent<Animator> ();
    18.         m_Rigidbody = GetComponent<Rigidbody> ();
    19.     }
    20.  
    21.     void FixedUpdate ()
    22.     {
    23.         float horizontal = Input.GetAxis ("Horizontal");
    24.         float vertical = Input.GetAxis ("Vertical");
    25.        
    26.         m_Movement.Set(horizontal, 0f, vertical);
    27.         m_Movement.Normalize ();
    28.  
    29.        
    30.        
    31.  
    32.         bool hasHorizontalInput = !Mathf.Approximately (horizontal, 0f);
    33.         bool hasVerticalInput = !Mathf.Approximately (vertical, 0f);
    34.         bool isWalking = hasHorizontalInput || hasVerticalInput;
    35.         m_Animator.SetBool ("IsWalking", isWalking);
    36.        
    37.  
    38.         Vector3 desiredForward = Vector3.RotateTowards (transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);
    39.  
    40.         m_Rotation = Quaternion.LookRotation (desiredForward);
    41.     }
    42.  
    43.     void OnAnimatorMove ()
    44.     {
    45.         m_Rigidbody.MovePosition (m_Rigidbody.position + m_Movement * m_Animator.deltaPosition.magnitude);
    46.         m_Rigidbody.MoveRotation (m_Rotation);
    47.     }
    48. }
    Thanks in advance!