Adding diagonal movement to a simple C# code

Hi guys,
So I have this code here that lets me move a player. It also rotates the player to face directions correctly. I wonder, how can I add diagonal movement to this code in the most effective manner?

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
    public float speed;
    //store the position of the player
    Vector3 pos;
    //Use this for initialization
    void Start () {
        //set the position to where we start off in the scene
        pos = transform.position;
        speed = 0.04f;
    }
    //Update is called once per frame
    void Update () {
        bool WKey = Input.GetKey(KeyCode.W);
        bool SKey = Input.GetKey(KeyCode.S);
        bool AKey = Input.GetKey(KeyCode.A);
        bool DKey = Input.GetKey(KeyCode.D);
        if(WKey) {
            pos.z += speed;
            transform.eulerAngles = new Vector3(0, 0, 0);

        }
        if(SKey) {
            pos.z -= speed;
            transform.eulerAngles = new Vector3(0, 180, 0);

        }
        if(AKey) {
            pos.x -= speed;
            transform.eulerAngles = new Vector3(0, -90, 0);

        }
        if(DKey) {
            pos.x += speed;
            transform.eulerAngles = new Vector3(0, 90, 0);

        }
        gameObject.transform.position = pos;
    }
}

It should already do diagonal movement, right? It’s just the direction you need. If I were you, I’d take the rotations out of the if statement, so that it says

        if(WKey) {
            pos.z += speed;
        }

etc., and then add this line before tranform.position = pos; :

gameObject.transform.LookAt(pos, new Vector3(0,1,0));

which points the object at the direction of movement, with up being the y-axis

1 Like

You rock! Thank you :slight_smile: