- Home /
Maintaining specific distance between two objects
So my game has two cars connected to each other via a script. The wheels of the cars have wheel colliders. Another script controls the movement of the cars such that when i press the forward button car1 goes ahead and car2 goes behind it in reverse (My game is only based on z axis). And when i press the reverse button car2 goes ahead and car1 in reverse. Now when i press the forward button, car2 reverses faster and collides with car1. Same goes when i press the reverse button. I want to maintain a specific distance between the two cars so that they dont collide at all. I am not able to figure how i can make this possible. Should I try by controlling the speed of the car?
This is my CarControllerScript. I have made two classes which contain reference for wheel colliders and wheels. Both of these classes contain Top Speed, current Speed, max torque and forward variables. (I know the rigidbody parameter in the function is not being used. I am going to remove it later. )
The Car on the left is Car1.
public Car car1;
public Car2 car2;
public void Forward (Rigidbody rb) {
//Formula for calculating speed
car1.currentSpeed = 2 * 22 / 7 * car1.WheelBL.radius * car1.WheelBL.rpm * 60 / 1000;
car2.currentSpeed = 2 * 22 / 7 * car2.WheelBL.radius * car2.WheelBL.rpm * 60 / 1000;
if (car1.currentSpeed < car1.topSpeed && car2.currentSpeed < car2.topSpeed){
// Run the back wheels of Car1
car1.WheelBL.motorTorque = car1.maxTorque * car1.forward;
car1.WheelBR.motorTorque = car1.maxTorque * car1.forward;
// Reverse Car2
car2.WheelBL.motorTorque = -car2.maxTorque * car2.forward;
car2.WheelBR.motorTorque = -car2.maxTorque * car2.forward;
}
}
public void Reverse (Rigidbody rb) {
//Formula for calculating speed
car2.currentSpeed = 2 * 22 / 7 * car2.WheelBL.radius * car2.WheelBL.rpm * 60 / 1000;
car1.currentSpeed = 2 * 22 / 7 * car1.WheelBL.radius * car1.WheelBL.rpm * 60 / 1000;
if (car2.currentSpeed < car2.topSpeed && car1.currentSpeed < car1.topSpeed){
// Run the back wheels of Car2
car2.WheelBL.motorTorque = car2.maxTorque * car2.forward;
car2.WheelBR.motorTorque = car2.maxTorque * car2.forward;
// Reverse Car1
car1.WheelBL.motorTorque = -car1.maxTorque * car1.forward;
car1.WheelBR.motorTorque = -car1.maxTorque * car1.forward;
}
}
Answer by BIO_K · Jun 07, 2018 at 01:00 PM
I can give you bit from a script I made... I check all my distances using this... You can ofcourse tweak it however...
if (Vector3.Distance(player.position, thisTransform.position) < 3)