How to make a 4-way movement script Unity 2D C#

[By JayDev64x] [Index]

This is how to make a 4-way movement script within Unity 2D. The speed can be changed in the inspector and the movement is consistent since it is multiplied by Time.deltaTime.

using UnityEngine; public class Movement : MonoBehaviour { public float speed = 5; void Update() { if (Input.GetKey("w")) { gameObject.transform.position += new Vector3(0, speed * Time.deltaTime); } if (Input.GetKey("a")) { gameObject.transform.position += new Vector3(-speed * Time.deltaTime, 0); } if (Input.GetKey("s")) { gameObject.transform.position += new Vector3(0, -speed * Time.deltaTime); } if (Input.GetKey("d")) { gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0); } } }

Created [September 6, 2021]