- Home /
The problem was found.
[Solved] Unity rigidbody.addForce ignores time.deltaTime? Possibly just a code bug I cannot find.
EDIT: The issue was resolved quite quickly. The problem was me multiplying the maxSpeedSquared with maxSpeed instead of equaling it to maxSpeed multiplied with maxSpeed. I also learnt something new, so for those that stumbled upon this question in search of an answer for a similar problem should also note that physics should be done in FixedUpdate().
Hello there. I've been trying to do a simple acceleration of a rigidbody and deceleration when I release the acceleration button (in this case the "W" key). Also a top speed and a faster deceleration when I push a button to "brake" (in this case the space bar.)
I got everything working - apart from the acceleration. Somehow, the rigidbody.addForce method I am using combined with time.deltaTIme won't add a force once every second - it adds it constantly, or at least my rigidbody accelerates to maxSpeed instantlyinstantly. Please see the code to see what I did. This might be caused by the way I handle the top speed - however I have been trying to figure this out since over half an hour now and still cannot seem to find the bug in the code. Could you please help me with this? I am sure I'm just overlooking something simple.
public float speed;
public float maxSpeed; // The maximal speed
public float accelerationSpeed; //The acceleration speed (or multiplier)
private Rigidbody rig; // To not always have to do GetComponent()
private Vector3 speedVec = new Vector3 (0,0,0); // To not always have to make a new vector but rather just keep changing it
private float maxSpeedSquared; // Since rigidbody.velocity.sqrMagnitude returns a squared number, I need to do the same for my max speed to even it out. (10 turns into 100, while velocity with 10 would be 100 squared, which the sqrMagnitude returns.)
// Use this for initialization
void Start () {
rig = this.GetComponent<Rigidbody> ();
maxSpeedSquared *= maxSpeed;
}
// Update is called once per frame
void Update () {
speedVec = rig.velocity;
speed = speedVec.sqrMagnitude;
if (Input.GetKey (KeyCode.W)) {
if (rig.velocity.sqrMagnitude > maxSpeedSquared) {
rig.velocity = speedVec.normalized * maxSpeed;
} else {
rig.AddForce(transform.forward * accelerationSpeed * Time.deltaTime);
}
}
if (Input.GetKey (KeyCode.Space)) {
rig.drag = 2; // When no force is added, the rigidbody drag decelerates it, normally it's set to 1 but in order to "brake" e.g. decelerate faster I set it to 2.
}
}