- Home /
How can i add a timer to this code
Hi i am making a racing type game and i would like to know how to make a timer that starts when the car starts moving is that possible and if so how would i do it.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Car : MonoBehaviour { private Rigidbody carRigid; public int speed; public int rotatespeed;
// Use this for initialization
void Start () {
carRigid = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
}
void FixedUpdate (){
if (Input.GetButton ("Drive")) {
carRigid.AddForce (transform.forward * speed * Time.deltaTime);
}
if (Input.GetButton ("Reverse")) {
carRigid.AddForce (transform.forward * -speed * Time.deltaTime);
}
if (Input.GetButton ("Left")) {
transform.Rotate (0, -rotatespeed, 0);
}
if (Input.GetButton ("Right")) {
transform.Rotate (0, rotatespeed, 0);
}
}
}
Answer by Destolos · Aug 19, 2017 at 07:12 AM
First you have to check, when the car starts moving: if(carRigid.velocity > 0)
This some code of a timer, i once made, perhaps it will help you:
public long hour;
private long minute, second, milliseconds;
public float speed = 1;
void Update ()
{
milliseconds += (long)(Time.deltaTime * 1000 * speed);
if (milliseconds >= 1000)
{
second += milliseconds / 1000;
milliseconds %= 1000;
if (second >= 60)
{
minute += second / 60;
second %= 60;
if (minute >= 60)
{
hour += minute / 60;
minute %= 60;
if (hour >= 24)
{
hour %= 24;
}
}
}
}
}
Ok so would i add that code to the one i have now or make a whole new one and if i make a new one what item would i attache it too?
Your answer
Follow this Question
Related Questions
How to make a timer read to the .001 of a second 2 Answers
Best time and saving best time 3 Answers
Timer doesn't count 0 Answers
Lap Counter Bug 0 Answers