Search Unity

Question How to make a player face their movement direction

Discussion in 'Scripting' started by Crimson_404, Jun 22, 2020.

  1. Crimson_404

    Crimson_404

    Joined:
    Jun 21, 2020
    Posts:
    2
    Code (CSharp):
    1. public class move : MonoBehaviour
    2. {
    3.     public int speed;
    4.     // Start is called before the first frame update
    5.     void Start()
    6.     {
    7.      
    8.     }
    9.  
    10.     // Update is called once per frame
    11.     void FixedUpdate()
    12.     {
    13.         if (Input.GetKey(KeyCode.W))
    14.         {
    15.             transform.Translate(transform.forward * speed * Time.deltaTime);
    16.             transform.rotation = new Quaternion(0, 0, 0, 0);
    17.         }
    18.         if (Input.GetKey(KeyCode.A))
    19.         {
    20.             transform.Translate(transform.right * speed * Time.deltaTime * -1);
    21.             transform.rotation = new Quaternion(0, 270, 0, 0);
    22.         }
    23.         if (Input.GetKey(KeyCode.S))
    24.         {
    25.             transform.Translate(transform.forward * speed * Time.deltaTime * -1);
    26.             transform.rotation = new Quaternion(0, 180, 0, 0);
    27.         }
    28.         if (Input.GetKey(KeyCode.D))
    29.         {
    30.             transform.Translate(transform.right * speed * Time.deltaTime);
    31.             transform.rotation = new Quaternion(0, 90, 0, 0);
    32.         }
    33.     }
    34. }
    W and S parts work but A and D faces backwards.
    Note: I started C# yesterday.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,739
    Don't construct a Quaternion from those x,y,z,w arguments. Those are NOT angles.

    Instead, use the Quaternion.Euler() constructor:

    Code (csharp):
    1. transform.rotation = Quaternion.Euler( 0, 90, 0);
    Note the lack of
    new
    , as it is a factory method, not a ctor.
     
  3. Crimson_404

    Crimson_404

    Joined:
    Jun 21, 2020
    Posts:
    2
    Thank you for your help