Game Development Reference
In-Depth Information
Add the following function below the Update() function:
function OnControllerColliderHit (hit : ControllerColliderHit) {
var body : Rigidbody = hit.collider.attachedRigidbody;
if (body == null || body.isKinematic)
return;
if (hit.moveDirection.y < -0.3)
return;
var pushDir : Vector3 = Vector3 (hit.moveDirection.x, 0,
hit.moveDirection.z);
body.velocity = pushDir * pushPower;
}
This code breaks down as follows:
(1) function OnControllerColliderHit (hit : ControllerColliderHit) {
The Character Controller component has an OnControllerColliderHit function that is called if
the capsule hits another collider during a Move. ControllerColliderHit provides more detailed
information about the collision.
(2) var body : Rigidbody = hit.collider.attachedRigidbody;
Declares a Rigidbody type variable body to hold a reference to the rigidbody of the game object the
Cube collided with.
(3) if (body == null || body.isKinematic)
return;
Checks to see if in fact the other object has a rigidbody component OR if it is set to Is Kinematic.
If either of these is true, then the Cube cannot push it around, so the function is exited via the
return statement.
(4) if (hit.moveDirection.y < -0.3)
return;
This conditional is for checking the collision direction to prevent pushing any objects below the Cube.
(5) var pushDir : Vector3 = Vector3 (hit.moveDirection.x, 0,
hit.moveDirection.z);
Declares a Vector3 type reference variable pushDir to hold the moveDirection information from the
collision in the x and z axes.
(6) body.velocity = pushDir * pushPower;
The final response to the Cube's push is calculated by multiplying the push direction by your
pushPower factor and applying this velocity to the impacted object's rigidbody.
 
Search WWH ::




Custom Search