Home > database >  How to turn off inertia when player stops moving?
How to turn off inertia when player stops moving?

Time:11-25

When I release the character control button, character itself continues to move for about half a second. I want the character to stop right after I release the control button. I’ve tried diffirent methods: AddForce and velocity, but it’s all in vain.

Also, I tried to adjust the mass and drag momentum in Inspector of the character, but it didn’t help.

public class CapsuleMovement : MonoBehaviour
{
    Rigidbody rb;
    Vector3 playerMovement;
    [SerializeField] float speed = 50;
    
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        ProccessCapsuleMovement();
    }

    void ProccessCapsuleMovement () 
    {
        playerMovement = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        playerMovement.Normalize();

        rb.velocity = playerMovement * speed * Time.deltaTime;
    }
}

CodePudding user response:

  • Don't normalize! If the Input magnitude is actually smaller than 1 you still normalize it always to a magnitude 1!

    Rather use Vector3.ClampMagnitude which only limits the magnitude in the upper bound but allows it to be smaller

  • The other point might be that GetAxis is actually "smoothed" and not applied immediately! After releasing the button it is actually decreased over time. So since you normalized the vector it keeps having a magnitude of 1 for a while after releasing the buttons.

    You might rather want to use GetAxisRaw for this.

  • Then when assigning a velocity you do not want to multiply by Time.deltaTime! This only is needed where you want to convert a value from a fixed value per frame into a frame-rate-independent value per second. A velocity already is a vector per second so remove the * Time.deltaTime.

so something like e.g.

playerMovement = Vector3.ClampMagnitude(new Vector3 (Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")), 1f);

rb.velocity = playerMovement * speed;
  • Related