Search Unity

Question Rigidbody player won't turn properly

Discussion in 'Scripting' started by AlphaPrimeG, Jan 25, 2021.

  1. AlphaPrimeG

    AlphaPrimeG

    Joined:
    Jul 22, 2020
    Posts:
    8
    My character turn 90,180,270 and 360 degrees wheel, but when moving diagonally it moves a few degrees left or right...

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour
    2. {
    3.     //Move the rigidbody
    4.     //Face the input direction
    5.     //Rotate based on input
    6.  
    7.    
    8.     Rigidbody m_Rigidbody;
    9.     public float m_Speed = 5f;
    10.     public float rotationSpeed = 15;
    11.  
    12.     void Start()
    13.     {
    14.         //Fetch the Rigidbody from the GameObject with this script attached
    15.         m_Rigidbody = GetComponent<Rigidbody>();
    16.     }
    17.  
    18.     void FixedUpdate()
    19.     {
    20.         //Store user input as a movement vector
    21.         Vector3 m_Input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
    22.         //Vector3 inputDir = m_Input.normalized;
    23.         //Apply the movement vector to the current position, which is
    24.         //multiplied by deltaTime and speed for a smooth MovePosition
    25.         m_Rigidbody.MovePosition(transform.position + m_Input * Time.deltaTime * m_Speed);
    26.         //Input.y = 0;
    27.         RotateToward(m_Input);
    28.        
    29.     }
    30.  
    31.     private void RotateToward(Vector3 m_Input)
    32.     {
    33.         //(m_Input.magnitude == 0) {return;}
    34.         //if(Mathf.Approximately(m_Input.sqrMagnitude, 0))
    35.         //{
    36.         //    return;
    37.         //}
    38.         //if (Mathf.Approximately(m_Input.magnitude, 0) == true)
    39.         //    return;
    40.         //Quaternion rotation = Quaternion.LookRotation(m_Input);
    41.         //transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotationSpeed);
    42.        if (m_Input.magnitude >= 0.1f)
    43.         {
    44.             transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(m_Input), rotationSpeed * Time.deltaTime);
    45.         }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Two problems:

    1. You're using Quaternion.Lerp incorrectly. Your third parameter makes no sense. Lerp expects a 3rd parameter that moves over time from 0 to 1.
    2. If this is a rigidbody you should not set transform.rotation directly. Instead, use m_Rigidbody.MoveRotation()
     
  3. AlphaPrimeG

    AlphaPrimeG

    Joined:
    Jul 22, 2020
    Posts:
    8
    Thanks for help. I'm trying to learn it but I really don't understand... I'm looking for it a days...