Search Unity

How could I code a distance coutner for my game?

Discussion in 'Scripting' started by SneakingMilk, Nov 14, 2017.

  1. SneakingMilk

    SneakingMilk

    Joined:
    Mar 5, 2017
    Posts:
    7
    I'm currently making an endless game where the player has to dodge trees and wish to have a distance counter as a way of giving the player a score but I am unsure how to write a script to do this. The player is not actually moving in the scene, instead the obstacles are moving through the scene so it cant be done using the player game objects' transform.

    I had a go at making a script (attached below) that measured distance by multiplying the time by a factor of the obstacles' speed however this resulted in the distance not being reset to 0 when restarting the scene as Time.time was not going back to 0.

    I am very new to scripting so it would be greatly appreciated if someone could give me some sample code to help me with this problem.


    Code (CSharp):
    1. public class DistanceCount : MonoBehaviour
    2. {
    3.  
    4.     public Text distanceText;
    5.     private float startDistance;
    6.     public float speed;
    7.  
    8.     public GameObject tree;
    9.     private Mover mover;
    10.  
    11.     // Use this for initialization
    12.     void Start ()
    13.     {
    14.         startDistance = 0;
    15.         mover = tree.GetComponent<Mover> ();
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update ()
    20.     {
    21.         speed = mover.speed;
    22.         float d = (Time.time - startDistance) * (-speed/3);
    23.         string distance = ((int) d).ToString();
    24.  
    25.         distanceText.text = distance + "m";
    26.  
    27.     }
    28. }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    There are plenty of time options https://docs.unity3d.com/ScriptReference/Time.html

    You should be able to use the deltaTime call. Just keep a float variable that tracks time. Add the deltaTime to it, then use that in place of your Time.time.

    Or, just record the Time.time value at the start of the level (when the player starts moving) and use that value to subtract from whatever Time.time is as your player moves and then use that value in your Update call.
     
  3. BellevueJ

    BellevueJ

    Joined:
    Nov 14, 2017
    Posts:
    2