Source file unity-csharp/ebook/TopDownPlayerMovement.cs from the GDnD code examples. Download raw file

// Demonstrates Update input plus FixedUpdate physics movement for The Architecture of Play ebook.
// Referenced by: docs/ebook/GDnD-Architecture-of-Play.md
using UnityEngine;
 
[RequireComponent(typeof(Rigidbody2D))]
public class TopDownPlayerMovement : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 5f;
 
    private Rigidbody2D rb;
    private Vector2 moveInput;
 
    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }
 
    private void Update()
    {
        moveInput.x = Input.GetAxisRaw("Horizontal");
        moveInput.y = Input.GetAxisRaw("Vertical");
        moveInput = moveInput.normalized;
    }
 
    private void FixedUpdate()
    {
        rb.velocity = moveInput * moveSpeed;
    }
}