- Home /
Question by
ucefemad · Sep 28, 2014 at 09:56 PM ·
javascriptrigidbodycarforce
How to set max speed for this car ?
I made a code that applies a relative force to a rigidbody, I Calculate it's speed but it keeps increasing as long as I'm pressing the key, I want to add a MaxSpeed to this car so for example when it reaches 120, it keeps running on the same speed until I stop pressing the key, this is my code.
function Update () {
var enginePower = 99000;
var brakePower = 40000;
var speed = rigidbody.velocity.magnitude;
var maxSpeed = 120;
if(Input.GetKey(KeyCode.UpArrow)){
gameObject.rigidbody.AddRelativeForce(0,0,enginePower);
};
if(Input.GetKey(KeyCode.DownArrow)){
gameObject.rigidbody.AddRelativeForce(0,0,-brakePower);
};
Debug.Log(speed);
}
Comment
Best Answer
Answer by robertbu · Sep 28, 2014 at 09:57 PM
This will do the job:
function FixedUpdate() {
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, 120.0);
}
So how is it 'not' working? Can you provide the complete script? Change your Update() in your code to FixedUpdate() and integrate the line of code I suggest.