- Home /
Car Accelerate Over Time. (JavaScript and RigidBody)
Hello. This is my first post so please be gentle. I am working with Unity's Car Tutorialand trying to make the car accelerate by itself. I disabled the throttle and break functions in Car.js so the player can only steer left or right. My problem is creating a function that will make the car accelerate until it reaches the maxSpeed. Currently, the car will slowly move forward and at the same speed. I am also unsure if I need to call the function in Update() or FixedUpdate(). Any help will be greatly appreciated.
var curSpeed : float = 0.0; // holds current speed value
var acc : float = 10.0; // rate car accelerates at
var maxSpeed : float = 160.0; // max speed the car can go
function FixedUpdate()
{
// The rigidbody velocity is always given in world space, but in order to work in local space of the car model we need to transform it first.
var relativeVelocity : Vector3 = transform.InverseTransformDirection(rigidbody.velocity);
CalculateState();
UpdateFriction(relativeVelocity);
UpdateDrag(relativeVelocity);
ApplyAcceleration(relativeVelocity);
ApplySteering(canSteer, relativeVelocity);
}
function ApplyAcceleration(relativeVelocity)
{
curSpeed += acc;
curSpeed = Mathf.Clamp(curSpeed,-maxSpeed,maxSpeed); // Clamps curSpeed
rigidbody.AddForce(transform.forward * curSpeed * Time.deltaTime);
}
Answer by Crazy88 · Oct 07, 2011 at 08:23 AM
Thanks for your help. That link explained the Update/FixedUpdate much better then my teacher. Also, that if statement seems obvious now.
But my car still doesn't accelerate the way I want it too. My function uses three; variables; speed, topSpeed, and accRate.
I want the car to start at a speed of 0 and begin to accelerate at accRate until it reaches topSpeed. Right now my function looks like this:
function ApplyAcceleration(relativeVelocity)
{
if (speed < maxSpeed)
{
speed += accRate;
speed = Mathf.Clamp(speed,maxSpeed,Time.timeDelta); // Clamps current Speed
}
rigidbody.AddForce(transform.forward * speed);
}
The car is still moving very slow and I don't see any acceleration.
Answer by Meltdown · Oct 05, 2011 at 06:59 PM
Update your FixedUpdate function with this line...
if(curSpeed < maxSpeed)
ApplyAcceleration(relativeVelocity);
So the accelleration will be applied until the maxspeed has been reached.
Read this previous answer for an understanding of when to use Update and FixedUpdate.
Your answer
![](https://koobas.hobune.stream/wayback/20220612235724im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Car is not moving Straight with Acceleration Button Pressed 2 Answers
can't slow my car down 2 Answers
Car dynamics? 0 Answers
How to make car land on 4 wheels and maintain speed? 0 Answers