The Rigidbody component gives a GameObject a physical presence in the scene in that it is able to respond to forces. You could apply forces directly to the GameObject or allow it to react to external forces such as gravity or another Rigidbody hitting it.
You can add a Rigidbody by clicking Component > Physics > Rigidbody
It is recommended that if you apply a Rigidbody to a GameObject that you use forces or torque to move it rather than manipulating it's Transform. Use
AddTorque() methods for this:
// Add a force to the order of myForce in the forward direction of the Transform. GetComponent<Rigidbody>().AddForce(transform.forward * myForce); // Add torque about the Y axis to the order of myTurn. GetComponent<Rigidbody>().AddTorque(transform.up * torque * myTurn);
You can alter the mass of a Rigidbody GameObject to affect how it reacts with other Rigidbodies and forces. A higher mass means the GameObject will have more of an influence on other physics-based GameObjects, and will require a greater force to move itself. Objects of differing mass will fall at the same rate if they have the same drag values. To alter mass in code:
GetComponent<Rigidbody>().mass = 1000;
The higher the drag value, the more an object will slow down while moving. Think of it like an opposing force. To alter drag in code:
GetComponent<Rigidbody>().drag = 10;
If you mark a Rigidbody as Kinematic then it cannot be affected by other forces but can still affect other GameObjects. To alter in code:
GetComponent<Rigidbody>().isKinematic = true;
It is also possible to add constraints to each axis to freeze the Rigidbody's position or rotation in local space. The default is
RigidbodyConstraints.None as shown here:
An example of constraints in code:
// Freeze rotation on all axes. GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation // Freeze position on all axes. GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition // Freeze rotation and motion an all axes. GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll
You can use the bitwise OR operator
| to combine multiple constraints like so:
// Allow rotation on X and Y axes and motion on Y and Z axes. GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationX;
If you want a GameObject with a Rigidbody on it to respond to collisions you will also need to add a collider to it. Types of collider are:
If you apply more than one collider to a GameObject, we call it a Compound collider.
You can make a collider into a Trigger in order to use the
OnTriggerExit() methods. A trigger collider will not physically react to collisions, other GameObjects simply pass through it. They are useful for detecting when another GameObject is in a certain area or not, for example, when collecting an item, we may want to be able to just run through it but detect when this happens.