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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

player speed

Discussion in 'Scripting' started by hatman, Feb 27, 2009.

  1. hatman

    hatman

    Joined:
    Feb 3, 2009
    Posts:
    333
    I am controlling a camera using the fps script, is there a way to measure the players speed that he is moving?

    I somehow need to measure the change in the players x,y and z pos each frame and then divide this by time... any ideas?
     
  2. VoxelBoy

    VoxelBoy

    Joined:
    Nov 7, 2008
    Posts:
    240
    If you only need to measure speed between the previous frame and the current frame, then all you need to do is store the position information of the player object from the current frame into a Vector3, so that come next frame you can use it to calculate the difference.

    Here's a bit of code showing what I mean:
    Code (csharp):
    1.  
    2. Vector3 oldPosition = new Vector3();
    3.  
    4. void Update()
    5. {
    6.   //This is the global position of the game object
    7.   //that this script is attached to
    8.   currentPosition = gameObject.transform.position;
    9.  
    10.   //Calculate the distance between the position vectors of the current and the last frame
    11.   float distance = Vector3.Distance(currentPosition, oldPosition);
    12.   float speed = distance / Time.deltaTime;
    13.  
    14.   //We store the current position in another Vector
    15.   //so we can use it in calculations in the next frame
    16.   oldPosition = new Vector3(currentPosition.x, currentPosition.y, currentPosition.z);
    17. }
    18.  
    I hope this clears a few things up.
    -Yilmaz
     
  3. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    If you're using the FPSWalker.js script as it's provided it requires you to use the CharacterController component as well. And if that's the case then there's no need to track anything as the CharacterController exposes a velocity property already. Get that vector and its magnitude and you're all set.
     
  4. Nirav-Madhani

    Nirav-Madhani

    Joined:
    Jan 8, 2014
    Posts:
    27
    Doesnot work for me!