Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How do i make player to have a limit on velocity?

Discussion in '2D' started by El_barto8, Jun 8, 2022.

  1. El_barto8

    El_barto8

    Joined:
    Oct 22, 2020
    Posts:
    8
    Hello, how do i make player to have a max velocity?
    I tried using vector2.clampmagnitude, but it didnt work or i didnt did it well.

    Anyways, here is my code
    Code (CSharp):
    1. void Update()
    2.     {
    3.         horizontalSpeed = Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
    4.         verticalSpeed = Input.GetAxisRaw("Vertical") * speed * Time.deltaTime;
    5.        
    6.         rb2d.position += new Vector2(horizontalSpeed, verticalSpeed); //when i walk diagonally it goes faster than going straight, how do i set a cap
    7.     }
    Thanks
     
  2. Unrighteouss

    Unrighteouss

    Joined:
    Apr 24, 2018
    Posts:
    599
    Hey,

    The reason you're unable to clamp the velocity is because you're not setting the velocity, you're setting the position. If you put a debug line in your code, you'll be able to see that for yourself:
    Debug.Log(rb2d.velocity);
    .

    Here's an example of working code:
    Code (CSharp):
    1.     void Update()
    2.     {
    3.         horizontalSpeed = Input.GetAxisRaw("Horizontal") * speed;
    4.         verticalSpeed = Input.GetAxisRaw("Vertical") * speed;
    5.  
    6.         rb2d.velocity = new Vector2(horizontalSpeed, verticalSpeed);
    7.         rb2d.velocity = Vector2.ClampMagnitude(rb2d.velocity, speed);
    8.  
    9.         Debug.Log(rb2d.velocity);
    10.     }
    When setting velocity, you don't need to multiply by
    Time.deltaTime
    because velocity is already frame rate independent.

    If anything is unclear, please let me know.
     
  3. El_barto8

    El_barto8

    Joined:
    Oct 22, 2020
    Posts:
    8

    Thank you, have a nice day