Search Unity

I'm trying to understand why walking diagonally goes faster.

Discussion in 'Scripting' started by thiagoferos9, Jul 24, 2021.

  1. thiagoferos9

    thiagoferos9

    Joined:
    Jul 7, 2021
    Posts:
    3
    I'm new to C# and I'm creating a top down game for studies, but when I walk diagonally my character walks faster than normal, I've already researched it and I can't solve it, can someone help me? there is my script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public float moveSpeed = 5.5f;
    8.     public Rigidbody2D rb;
    9.     public Animator animator;
    10.     Vector2 movement;
    11.  
    12.  
    13.     void Start()
    14.     {
    15.  
    16.     }
    17.     void Update()
    18.     {
    19.         movement.x = Input.GetAxisRaw("Horizontal");
    20.         movement.y = Input.GetAxisRaw("Vertical");
    21.  
    22.         animator.SetFloat("Horizontal", movement.x);
    23.         animator.SetFloat("Vertical", movement.y);
    24.         animator.SetFloat("Speed", movement.sqrMagnitude);
    25.         if (this.movement.magnitude > 1)
    26.         {
    27.             this.movement = this.movement.normalized;
    28.         }
    29.  
    30.     }
    31.  
    32.     void FixedUpdate()
    33.     {
    34.         rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    35.     }
    36. }
    37.  
     
  2. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    2,073
    Because when you do
    movement * movementSpeed
    the resulting vector is longer than movementSpeed.

    You can do it like this
    movement.normalized * movementSpeed
     
    thiagoferos9 likes this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    I would do something like this:

    Code (CSharp):
    1.     void Update()
    2.     {
    3.         movement.x = Input.GetAxisRaw("Horizontal");
    4.         movement.y = Input.GetAxisRaw("Vertical");
    5.         movement = Vector3.ClampMagnitude(movement, 1f);
    6.         animator.SetFloat("Horizontal", movement.x);
    7.         animator.SetFloat("Vertical", movement.y);
    8.         animator.SetFloat("Speed", movement.sqrMagnitude);
    9.     }
     
  4. thiagoferos9

    thiagoferos9

    Joined:
    Jul 7, 2021
    Posts:
    3
    Thanks for the answer now I understand what I went wrong, now it's working perfectly
     
  5. thiagoferos9

    thiagoferos9

    Joined:
    Jul 7, 2021
    Posts:
    3
    Thanks, your took my doubts about vector, and it worked too!