- Home /
how do i gradually speed up a car
hi.
im a newbie ive been trying to make this car gradually speed up rather than it going from 0 to 100 instantly, with no sucess. any suggestions how i could do this.
public class moveCar : MonoBehaviour { public float moveSpeed = 0f; public float rotationSpeed = 1f;
void Start () {
}
void FixedUpdate () {
if (Input.GetKey (KeyCode.UpArrow ))
{
transform.Translate(Vector3.forward * moveSpeed);
if (Input.GetKey (KeyCode.LeftArrow))
{
transform.Rotate(-Vector3.up * rotationSpeed);
}
if (Input.GetKey (KeyCode.RightArrow))
{
transform.Rotate(Vector3.up * rotationSpeed);
}
}
}
}
?? By speed up, you mean you want the car to move? Because the Rotate command doesn't move -- it rotates.
Seems you'd fine lots of things other people have done, guides, ... searching things like "unity push object." If just reading the script is confusing, any intro to computer program$$anonymous$$g or to C# would help.
Answer by tanoshimi · Jan 27, 2015 at 04:05 PM
Just think through the logic/physics of what you want to achieve. At the moment, you're moving the car forward by moveSpeed
every frame in which the UpArrow is pressed. What you want to do is move the car forward by moveSpeed
every frame, but increase the moveSpeed when the UpArrow is pressed (and possibly decrease it when UpArrow is not pressed).
So, that would look something like:
void FixedUpdate () {
if (Input.GetKey (KeyCode.UpArrow )) {
moveSpeed += 1; // 1 here is the rate of acceleration
}
else {
moveSpeed -= 1; // 1 here is the rate of deceleration
}
transform.Translate(Vector3.forward * moveSpeed);
if (Input.GetKey (KeyCode.LeftArrow)) {
... etc. etc.
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613181656im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Car not accelerating 1 Answer
Void loop? 2 Answers
vehicle decceleration and angle reseting 1 Answer
Hit problem unity 1 Answer
How to reach a specific max speed with AddForce() ? 1 Answer