- Home /
Freeze Gameobject's position on collision
Im making a car AI where it goes to the enemy. When it collides with a game object other than the ground, I want it to freeze it's position and rotation (just stop the car.) Here is the code I have so far:
void OnCollisionEnter (Collision col)
{
if (col.gameObject.name == "Ground") {
//Do nothing
} else {
// freeze car here
print ("froze");
}
}
This script is attached to the car, the car has a rigid body and box collider. I have tried these lines of code to stop the car
GetComponent<Rigidbody>().GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY;
transform.position = Vector3.zero;
theRigidbody.velocity = Vector3.zero;
this.GetComponent<Rigidbody>().useGravity = false;
Setting a game object's position manually when using physics does usually not give the results you intend. Are you trying to have the car brake/decelerate or actually freeze (as in completely stopping within a single frame)?
Your answer
Follow this Question
Related Questions
RigidBody immediately stops after AddForce 1 Answer
Looking for some advice for a Horse with Rigidbody 0 Answers
rigidbody2D.addforce in collider 1 Answer
Door Not Colliding 0 Answers
Distribute terrain in zones 3 Answers