Okay, I have two cubes in a scene, one above the other. Both have rigidbody, with a box collider beneath (in the inspector). The rigidbody on top has the following code:
var hit : RaycastHit;
function Start () {
this.rigidbody.AddForce(Vector3(0,-200,0) );
}
function Update () {
if (this.rigidbody.SweepTest(Vector3(0,-1,0), hit, 2 * Time.deltaTime) ) {
print("detected");
rigidbody.velocity = Vector3.zero;
}
}
This is supposed to cause it to drop down until it reaches the lower rigidbody, and then stop. However, the top rigidbody just keeps going right through the bottom one, and there is no “detected” in the console. What am I doing wrong?
I don’t know if this will fix it, but it will definitely avoid many problems.
The rigidbody system uses a separate runtime loop called FixedUpdate, which runs at fixed intervals. There is no guarantee in which order or if at all FixedUpdate and Update will be called. You might get 12 FixedUpdate calls before you get a single Update.
This means that your rigidbody might already collie with your other cube before the SweepTest even happens.
In this case you would use rigidbody.velocity.magnitude as the maximum length of the SweepTest
My suggestion would be, to move your SweepTest into FixedUpdate instead of Update.
As I post this I question myself more and more why you would do that? RIgidbodies already collide and perform physics by themselves. There is no need to do a SweepTest to stop things from going through each other. If you wanted something to stop when it collides you should use OnCollisionEnter or OnCollisionStay.