Not quite sure if I'm using Time.deltaTime correctly?

Hi again everyone,

I have a small racing game that is near complete, but I have noticed some odd behaviour recently… when you run it in the faster graphics modes, the acceleration and braking increases a LOT and renders the game almost unplayable. I figure this is down to my use of Time.deltaTime… I obviously want the game to run exactly at the same speed, no matter what machine it is running on. Where am I going wrong? Cheers!

if (!bCarDestroyed)
 {
 // If W key is pressed, accelerate
 if (Input.GetKey("up") && g_fSpeed < g_fMaxSpeed || Input.GetButton("GasP1") && g_fSpeed < g_fMaxSpeed)
 { 
 g_fSpeed += g_fAcceleration;
 transform.Translate(0.0f, 0.0f, g_fSpeed * Time.deltaTime);
 }
 // If S key is pressed, brake
 else if (Input.GetKey("down") || Input.GetButton("BrakeP1"))
 {
 // Disable boost
 g_bBoostEnabled = false;
 
 if (g_fSpeed > 0.0f) // Brakes only work if car is moving
 {
 g_fSpeed -= fBrakeForce;
 transform.Translate(0.0f, 0.0f, g_fSpeed * Time.deltaTime);
 }
 }
 // If no input, slow down gradually
 else
 {
 if (g_fSpeed > 0.0f) // So that car doesn't move in reverse when comes to stop
 {
 g_fSpeed -= fDecceleration;
 transform.Translate(0.0f, 0.0f, g_fSpeed * Time.deltaTime);
 }
 }
 }

As a car game I would recommend to use AddForce and rigidbody instead. A car in real world uses force provided by the engine, you can reproduce the same principle here. Braking is simply applying an inverse force until both are equal.

This would give it a more natural feeling.

Then you can use FixedUpdate which has a user designed fps and then the same on all machine.

Change in velocity needs some deltaTime love’n as well…

g_fSpeed += g_fAcceleration * Time.deltaTime;

g_fSpeed -= fBrakeForce * Time.deltaTime;

g_fSpeed -= fDecceleration * Time.deltaTime;

When velocity is integrated to get position, the result will include a time squared term, that being acceleration.
V(t) = Vo + At ; where Vo is the initial velocity and A is acceleration
X(t) = ∫ V(t) dt = Vo
t + (A/2)*t^2 + C ; And C in this case will be initial position