- Home /
Move Player Car in Forward Direction using Physics Force
I was working on 3d car game where I want to move player car using given force. Here is gameplay snapshot:
At present, I have controlled the movement of a car using physics velocity.
Here is car forward direction movement code:
appliedSpeed += Time.fixedDeltaTime * 7f;
appliedSpeed = Mathf.Min (appliedSpeed, speed);
myRigidbody.velocity = transform.forward * appliedSpeed;
Here is car rotation code based on keyboard input:
// Rotate the car based on the control direction
// thisTransform.localEulerAngles += Vector3.up * rotateDirection * rotateSpeed * Time.deltaTime;
myRigidbody.rotation = myRigidbody.rotation * Quaternion.Euler (Vector3.up * rotateDirection * 5f);
Now rather than velocity, I want to use physics force as per this game requirements.
I have tried this:
if (myRigidbody.velocity.magnitude < 5f)
myRigidbody.AddRelativeForce (transform.forward * appliedSpeed, ForceMode.Force);
But can't able to get the desired result, its just moving into one direction only - based on car rotation, its force didn't get changed so please give me some suggestions into this.
One important reference, I found from here: Use AddRelativeForce - which adds a force to the rigidbody relative to its / local coordinate system
Answer by Ady_M · Jan 03, 2019 at 11:47 PM
When using AddRelativeForce, don't use transform.forward.
Use Vector3.forward instead.
These lines do the exact same thing:
myRigidbody.AddRelativeForce (Vector3.forward)
myRigidbody.AddForce (transform.forward)
myRigidbody.AddForce (transform.rotation * Vector3.forward)
Yes, I got your point and updated the code but I was getting this kind of problem from first. I have recorded one video for this: car physics behavior