Diagonal Movement

Hi!
When the player is moving diagonally he goes faster then when he moves horizontally or vertically.
I know I need to use Vector2.Normalize() but I can’t figure out how for the data we have in this lecture.

Thanks in advance to all who will reply!

Hi Mago,

You are right. Use the x and y value in a new Vector2. Then call the Normalize method on it and multiply the result with your speed. Do that for the entire movement, not just when you move your player diagonally.

Did this help?


See also:

Hi Nina,

I don’t know how to implement what you’re saying.
Can you give me an example modifying my code below?

private void Move()
    {
        float deltaX = Input.GetAxis("Horizontal") * Time.deltaTime;
        float deltaY = Input.GetAxis("Vertical") * Time.deltaTime;

        float newPosX = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax);
        float newPosY = Mathf.Clamp(transform.position.y + deltaY, yMin, yMax);

        Vector3 movement = new Vector3(newPosX, newPosY);
        movement.Normalize();
        movement *= moveSpeed;

        transform.position += movement;
    }

Your code is almost correct, so I’m giving you a few hints only. :slight_smile:

  1. The movement vector does not have anything to do with the position, just with the user input.
  2. Unless I’m wrong, Normalize() does not modify the Vector3 object but returns a new Vector3 object.
  3. You want to clamp the position after the movement/shift/transition.

Add Debug.Logs to your code to see what the values of your variables are during runtime. That’ll help you understand what’s going on while the game is running.

Feel free to share your code here if you get stuck or if you managed to make it work.

1 Like

Thank you a lot Nina!

I just managed to make it work following your steps and using the Debug.Log.

I also have discovered that Normalize() does modify the vector normalizing it, just like ToString() that turns an object into a string.

Here is my solution hoping it will help someone in the future:

private void Move()
    {
        Vector2 movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        movement.Normalize();
        movement *= Time.deltaTime * moveSpeed;

        float playerPosX = transform.position.x + movement.x;
        float playerPosY = transform.position.y + movement.y;

        transform.position = new Vector2(Mathf.Clamp(playerPosX, xMin, xMax), Mathf.Clamp(playerPosY, yMin, yMax));

        //transform.position = (Vector2)transform.position + movement;
        //transform.position = new Vector2(Mathf.Clamp(transform.position.x + movement.x, xMin, xMax), Mathf.Clamp(transform.position.y + movement.y, yMin, yMax));
        //Debug.Log(transform.position.x + " " + transform.position.y);
    }

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Good job! :slight_smile:

Privacy & Terms