So, I want to make a very simple driving script.
I finally got it to working almost the way I want to, exept one thing:
When W is not pressed, the current speed should be decreased by a fixed value per second, so the car doesn’t stop instantly.
Obviously using Time.deltaTime is the way to go, but for this part of the script it doesn’t seem to work - the value is subtracted each frame instead of each second.
I’m checking my script for hours now, tinkering with values and brackets, but i can’t find my error.
Here’s my code:
var acceleration : float = 0.0;
var maxSpeed : float = 10.0;
var speed : float = 0.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
var rotationSpeed : float = 5;
var gear : int = 0;
var gearcheck : int = 0;
function Start (){
acceleration = 0.0;
speed = 0.0;
maxSpeed = 20.0;
rotationSpeed = 3;
}
function Update (){
var controller : CharacterController = GetComponent(CharacterController);
// Acceleration to 0 on gear change
//set comparison gear
gearcheck = gear;
//set gear ( = direction)
if (Input.GetAxis("Vertical") > 0){
gear = 1;
}
else if(Input.GetAxis("Vertical") < 0){
gear = -1;
}
// compare gears/directions ( set acceleration to 0 on change)
if (gear != gearcheck){
acceleration = 0;
}
//Driving
if (Input.GetAxis("Vertical")){
speed = (Input.GetAxis("Vertical"))* acceleration;
transform.Translate(Vector3(0, speed, 0)* Time.deltaTime);
// accelerating (while speed < maxspeed)
if (acceleration < maxSpeed){
acceleration = acceleration +7 * Time.deltaTime;
}
}
// decrease of speed (when no input is given)
// THIS IS WHERE I THINK MY PROBLEM IS LOCATED
else if (speed > 1.6 || speed < -1.6){
speed = speed -(-gear * 2) * Time.deltaTime ;
transform.Translate(Vector3(0, speed , 0)* Time.deltaTime);
}
else {
acceleration = 0;
speed = 0;
}
// steering
if (speed != 0){
transform.Rotate (Vector3 (0, 0, Input.GetAxis("Horizontal") * rotationSpeed * speed) * Time.deltaTime );
}
print("Accelleration: " + acceleration + " / Speed: " + speed + " / Gear: " + gear);
}
Thanks in advance