Player Movement 2D Top Down (normalized)

Hello, I am new to Unity and Coding in general, and I had a bit of a struggle with diagonal movement of my Player in a top down 2D environment (Think RPG). I think I finally figured it out and thought I would share it for document my own progress and to help other newbies that have no clue. Wading through all the unhelpful half solutions was really off putting, so here’s what I came up with, maybe it helps some lost starter:

using UnityEngine;

public class WalkingScript : MonoBehaviour
{

    public Rigidbody2D BodyPlayer;
 
    private float horizontal;
    private float vertical;
    public float Speed = 350;

    private Vector3 movement;

    // Start is called before the first frame update
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical");
    }

    private void FixedUpdate()
    {

        movement = new Vector3(horizontal, vertical, 0).normalized;
        BodyPlayer.velocity = new Vector3(movement.x * Speed, movement.y * Speed, movement.z * Speed) * Time.fixedDeltaTime;




        Debug.Log(movement);
    }
}

Here’s the same code with remarks how I understood the functions and how they work. I beg for corrections and optimisations, I’m new and uneducated, and honestly, the Unity documentation is pretty bad if you’re not coming froma coding background.

using UnityEngine;

public class WalkingScript : MonoBehaviour  // It's this Script
{

    public Rigidbody2D BodyPlayer;  // You have to give your Character Physics first in Unity so you can use it in this Script.
 
    private float horizontal;  // declaring the variable where the horizontal Player Input will be stored.
    private float vertical;    // same for the vertical Input
    public float Speed = 350;  // variable for the Player Speed. I set it to public so I can change it during testing.

    private Vector3 movement;  // creating a variable that can store information of the position x, y and z.

    // Start is called before the first frame update
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal"); // stores the user input into the variable horizontal
        vertical = Input.GetAxisRaw("Vertical"); // same for vertical inputs
    }

    private void FixedUpdate()
    {

        movement = new Vector3(horizontal, vertical, 0).normalized; // this takes the values stored in horizontal and vertical and makes them always add to 1, so diagonal movement isnt faster than horizontal or vertical
        BodyPlayer.velocity = new Vector3(movement.x * Speed, movement.y * Speed, movement.z * Speed) * Time.fixedDeltaTime; // this moves the Player Sprite by applying new values to the coordinates of it. The normalized vectors that are stored in 'movement' are used and applied to each axis of the player. DeltaTime makes your Speed tied to a fixed Clock rather than the processor, so it does run the same speed on all machines.




        Debug.Log(movement); // this shows you the normalized current values in the debug window when you run the scene
     
    }
}

Bonus - My Code that also includes a running function:

using UnityEngine;

public class WalkingScript : MonoBehaviour
{

    public Rigidbody2D BodyPlayer;
    public float WalkingSpeed = 850;
    public float RunningSpeed = 1125;

    private float horizontal;
    private float vertical;
    private float Speed;

    private Vector3 movement;

    // Start is called before the first frame update
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical");

        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.Joystick1Button1))
        {
            Speed = RunningSpeed;
        }
        else
        {
            Speed = WalkingSpeed;
        }

    }

    private void FixedUpdate()
    {

        movement = new Vector3(horizontal, vertical, 0).normalized;
        BodyPlayer.velocity = new Vector3(movement.x * Speed, movement.y * Speed, movement.z * Speed) * Time.fixedDeltaTime;




        Debug.Log(BodyPlayer.velocity);
        Debug.Log(movement);

    }
}

The Unity documentation is for developers so if you have no coding experience, it’s not going to help you much. That’ll be more what video tutorials are for or the online Learn material that goes through things step-by-step. This doesn’t make it bad although I totally agree it’s far, far from perfect.

2D use Vector2 so you don’t need to use Vector3 and set the Z value to zero.

BodyPlayer.velocity = new Vector3(movement.x * Speed, movement.y * Speed, movement.z * Speed) * Time.fixedDeltaTime;

Here too, use Vector2 and not Vector3. If you are ever in doubt, use the scripting reference; in this case Rigidbody2D.velocity and you’ll see it states Vector2. Unity converts Vector3 to Vector2 for you implicitly but this can be the source of subtle errors, especially when normalising these vectors i.e. if Z wasn’t Z then normalising it and converting to 2D wouldn’t give you the correct vector.

Also, in your code, 2D cannot have a “z speed”, again that’d be 3D. Setting absolute velocity doesn’t need time-integrating (* Time.fixedDeltaTime) as it’s not a change over time. It’s like me saying my age is 50 * Time.fixedDeltaTime. I might want to increase my age by Time.fixedDeltaTime to ensure that it increases in a frame-independent way.

You’re correctly reading per-frame input in “Update” and only applying physics changes in “FixedUpdate” which is when (by default) physics runs. That said, this is normally only needed when you do things like adding forces, setting absolute values is fine. They won’t be processed until the physics runs but there’s no harm in doing it, it’s just a little wasteful.

Beyond that, I don’t see an issue and you even used code-tags in your first post so thank! :slight_smile:

Hope that helps.

[QUOTE="MelvMay, post: 9702731, member: 287484

Also, in your code, 2D cannot have a “z speed”, again that’d be 3D.

Hope that helps.[/QUOTE]

Thank you very much, that’s indeed very helpful, especially in regards of wrapping my head around how Unity functions.

I’m aware of Vector2, but I figured it doesn’t harm to still use Vector3, since from my understanding Unity is always kind of using 3 vectors, even in 2D engine mode, and I intended to play with the Z axis next.

So you’re saying that it doesn’t work that way because I use 2D physics for my body and it doesn’t apply the Z axis at all, even if I tried? You really made me think here and I’m mad I’m not at home to try it out and reconsider switching to 3D.

Alright, I understand the delta time now, or better said the difference bet
ween update and fixed update.

Thanks so much. I will add a fixed version later when I’m at home.

Yes Transform is Vector3 but no, 2D physics uses 2D vectors in all its API. This shouldn’t be a surprise being as it’s 2D and I don’t mean that to sound patronising at all!

2D physics has 3 degrees of freedom: XY position and Z rotation only. It doesn’t matter where you place the Transform component position Z (this is the Transform, not physics), 2D physics doesn’t care about it. Internally it only has those 3 degrees of freedom.

Here’s the API for what the Rigidbody2D knows for position: Rigidbody2D.position

When the simulation runs, it’ll write the XY part of the Transform position but leave the Z position untouched.

Thanks for the script you are so awesome sauce.