Calculating Player Speed gives inconsistent values

public class PlayerController : MonoBehaviour
{
    Vector3 playerPosition = new Vector3 (0, 0, 0);
    Vector3 oldplayerPosition = new Vector3 (0, 0, 0);
    Vector3 playerSpeed = new Vector3 (0, 0, 0);

    void Update ()
    {
        GameObject player = GameObject.Find ("Player");
       
        Rigidbody rbPlayer = player.GetComponent<Rigidbody> ();
        oldplayerPosition = playerPosition;
        playerPosition = rbPlayer.position*100;

        playerSpeed = playerPosition - oldplayerPosition;
        Debug.Log (playerSpeed);
    }
}

This piece of Code is supposed to calculate the Player Speed as a global Vector (I’m using a Character Controller). However when I Debug.Log it gives me very inconsistent values (anything between say 2 and 15). I’ve tried putting it into FixedUpdate but to no avail. Can anyone help me get the speed of the PlayerController accurately?

I need it to add to the speed to a grenade or whatever the character is supposed to throw (So a grenade doesn’t go straightahead when you throw it while straving sidewards)

Several issues at your code:

  • You are missing the time. Speed = position-change over time.
  • I don’t see the point of multiplying the position by 100.
  • You should also use “transform.position” instead of reading the position from the rigidbody. The rigidbody updates its position at FixedUpdate rate, while the Update method may be called at a different rate.

The correct calculation is:

playerSpeed = (transform.position - oldplayerPosition) / Time.deltaTime;
oldPlayerPosition = transform.position;

However, you might also read the speed directly from the rigidbody, if you have one:

playerSpeed = rbPlayer.velocity;
1 Like