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 go about limiting the magnitude of a vector velocity w/o affecting its relative direction?

Discussion in 'Physics' started by C456, Feb 10, 2023.

  1. C456

    C456

    Joined:
    Apr 25, 2022
    Posts:
    2
    This was my attempt:
    Basically, I have an an Rigidbody I call "Hitbox", and an empty "Eyes", as its child. When I press wasd keys my player moves. But somehow the direction of its movement is a little skewed; it goes sideways in a subtle way.
    I am pretty sure the error is in this piece of code:

    What I believe this code is failing at doing is translating the direction of the transform to "Eyes".

    Code (CSharp):
    1. if (Hitbox.velocity.magnitude > max_speed)
    2.         {
    3.  
    4.             Vector3 HitboxVectors = new Vector3(Mathf.Clamp(Hitbox.velocity.x, -max_speed, max_speed), Hitbox.velocity.y, Mathf.Clamp(Hitbox.velocity.z, -max_speed, max_speed));
    5.             Hitbox.velocity = Eyes.transform.InverseTransformDirection(HitboxVectors);
    6.  
    7.         } //Limit horizontal velocity
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,903
    If you want to set the magnitude of a vector to 1.0f, you use
    myVector.normalized
    or
    myVector.Normalize()
    .

    If you want to set it to any other particular length, just do
    myVector = myDesiredLength * myVector.normalized
    . You'll end up with NaN values if your original value was Vector.zero.
     
  3. C456

    C456

    Joined:
    Apr 25, 2022
    Posts:
    2
    How would this solve the issue that I have?
    Somehow it's affecting the direction, or not taking it in count.
     
  4. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,690
    Normalizing a vector, or multiplying a vector by a scalar won’t change its direction, only its magnitude.

    Your code clamps each component in the vector separately, don’t do that. Instead, calculate the magnitude of the vector, clamp it to the maximum desired magnitude (max_speed) then normalize the vector and multiply it by the clamped magnitude.
     
  5. karliss_coldwild

    karliss_coldwild

    Joined:
    Oct 1, 2020
    Posts:
    530
    arkano22 likes this.
  6. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    717
    Are you applying a force to a moving object? If so, then changing the magnitude of the force will change the resulting direction (unless the force is parallel to the direction of movement).

    Imagine lightly tapping a moving object versus hitting it with a sledgehammer. The resulting speed and direction will vary.