Hello,
I have a car, which is a rigidbody, and it’s moving on the Z axis only. I wish to change lanes on the press of a button. So for example; the car is now driving on x:220, when i press a button, the car moves to x:215.
Now, moving the car to that position is not really a problem, but i want it to look smooth, so it kinda steers towards it, and doesn’t lose speed or anything, and it will stay on x:215 until i switch again. I can’t find anything about translating rigidbodies smoothly, except the lerp function, which does not quite do what i want.
Can anyone point me in the right direction? Any help is appreciated!
Doing this with forces is very complex - you would have to write a PID controller, and it’s not easy to adjust its parameters. A much easier way to do that is using Mathf.MoveTowards:
var sideSpeed: float = 2.5;
var xPosition: float;
function Start(){
xPosition = transform.position.x;
}
function FixedUpdate(){
var pos = rigidbody.position;
pos.x = Mathf.MoveTowards(pos.x, xPosition, sideSpeed * Time.deltaTime);
rigidbody.position = pos;
}
This will smoothly move the rigidbody in the X axis only to the desired xPosition. To change the car to a lane 5 meters to the right, for instance, just do this:
xPosition -= 5;
and the car will move at sideSpeed meters per second to the new coordinate.
If you want a smoother change, use Lerp instead:
pos.x = Mathf.Lerp(pos.x, xPosition, sideSpeed * Time.deltaTime);
The car will not move at constant speed, but in a constant time: it will start moving fast, and reduce the lateral speed slowly when reaching the desired position, taking the same time no matter how far the new lane is. Just to give you an idea, sideSpeed = 5 will move the car to the new lane in about 1 second.
NOTE: The car will not steer to the new lane; you can fake this steering by changing the car rotation based on the distance pos.x->xPosition:
...
pos.x = Mathf.MoveTowards(pos.x, xPosition, sideSpeed * Time.deltaTime);
rigidbody.position = pos;
// adjust this number to get the desired angle:
var angle = (xPosition - pos.x) * 2.3;
transform.eulerAngles = Vector3(0, angle, 0);
...