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

Character facing world z direction when stop moving?

Discussion in 'Scripting' started by lTimesl, Jul 27, 2019.

  1. lTimesl

    lTimesl

    Joined:
    Feb 7, 2019
    Posts:
    8
    hello there i have problem hope to find help to understand how to fix it
    my problem is when the character stop moving it always change the direction it face to the world z direction
    i really cant figure it out how to fix
    i tried lookat() but this end that he never face the direction when moving

    the code i use

    Code (CSharp):
    1. public class MovementController : MonoBehaviour
    2. {
    3.     Vector3 _CharacterDirection;
    4.     Quaternion _CharacterRotation=Quaternion.identity,_Look;
    5.     Animator _CharacterAnim;
    6.     Rigidbody _CharacterRigidbody;
    7.     public float TurnSpeed;
    8.  
    9.     void Start()
    10.     {
    11.         _CharacterAnim = GetComponent<Animator>();
    12.         _CharacterRigidbody = GetComponent<Rigidbody>();
    13.     }
    14.  
    15.     void FixedUpdate()
    16.     {
    17.         CharacterMovement();
    18.     }
    19.  
    20.     void CharacterMovement()
    21.     {
    22.         float h = Input.GetAxis("Horizontal");
    23.         float v = Input.GetAxis("Vertical");
    24.         _CharacterDirection.Set(h, 0, v);
    25.         _CharacterDirection.Normalize();
    26.  
    27.         bool _IsHorizontalChange = !Mathf.Approximately(h, 0f);
    28.         bool _IsVerticalChange = !Mathf.Approximately(v, 0);
    29.         bool _IsWalking = _IsHorizontalChange || _IsVerticalChange;
    30.         _CharacterAnim.SetBool("IsWalking", _IsWalking);
    31.  
    32.          Vector3 _DesairdForward = Vector3.RotateTowards(Vector3.forward, _CharacterDirection, TurnSpeed * Time.deltaTime, 0);
    33.         _CharacterRotation = Quaternion.LookRotation(_DesairdForward);
    34.        
    35.  
    36.         _CharacterRigidbody.MovePosition(_CharacterRigidbody.position + _CharacterDirection * Time.deltaTime);
    37.         _CharacterRigidbody.MoveRotation(_CharacterRotation);
    38.        
    39.     }
     
  2. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    In line 32 you specify _DesairdForward by using Vector3.forward. That's world Z direction. You probably want this.transform.forward
     
  3. lTimesl

    lTimesl

    Joined:
    Feb 7, 2019
    Posts:
    8
    as i understand i use this to rotate the character while moving to make it face his z direction is this right??
     
  4. lTimesl

    lTimesl

    Joined:
    Feb 7, 2019
    Posts:
    8
    thank you