Getting speed without Rigidbody.velocity.magnitude

Hi there! I’m working on a game where the longer the player stays moving the more they accelerate and I made this code to to check if player is moving above a certain speed.

void FixedUpdate ()
    {
        if (player.velocity.magnitude >= 2)
        {
            print("true" + player.velocity.magnitude);
            player.AddRelativeForce(Vector3.forward * 1.5f * Time.deltaTime);
        }
        else
        {
            print("false" + player.velocity.magnitude);
        }
	}

However player.velocity.magnitude always returns zero (I’ve also checked if player is equal to the correct Rigidbody and it is)

I searched a bit online and apparently it’s something about the FPCharacter altering the speed directly so the Rigidbody doesn’t know the speed, yet none of them gave an alternative of checking the speed.
Is there even a way to do this?

All help appreciated :smiley:

You need to store position of the object one frame before and use some something similar like this (transform.position - oldPosition).magnitude / Time.deltaTime or fixedDeltaTime if you wish to do everything in FixedUpdate.

Few notes:

  1. The speed you get is in world space. You will probably need to do Mathf.Abs(theSpeedCalculation) to get it without negative numbers. And also, you might need not to take Y axis in to account. To do that, just set the Y position of the old position to the current Y position.
  2. normalized speed calculation is quite expensive. It computes a cubic root everytime. If you just need to check if the speed is higher than specific value and do not need to use speed in other calculations, you can use sqrMagnitude instead of magnitude to get a non cubic rooted value. Then compare speed to the value cubed or multiplied 3 times together. This will achieve what you need.