Unity Physics: Using The Force
With great physics, comes great responsibility. Now that we have become comfortable with collisions and triggers, let’s dive into some fun stuff adding force to some objects.
For this example I am going to punt this box into the portal ahead.
The box object has a rigidbody, collider and this Use The Force script attached to it. The Force value is used to multiply by the Vector 3 direction the force is being applied to.
I am just pushing the cube forward once in void start, and the only reason it get’s off the ground is because of it’s immediate position where it is colliding with the floor.
You can add Torque to have the object spin on an axis.
I add another force for upwards movement so the box can arc into the portal like a football through the uprights.
This script uses the rigidbody to push the game object. Add Relative Force will use the objects local direction, rather than the global direction that comes with Add Force.
Regardless of if you choose to use global or local directions with your force, both options take parameters of a Vector3 direction, as well as optional force modes.
Add Torque and Add Relative Torque are used for object rotations and also take parameters for a Vector3 and an optional force mode.
[RequireComponent(typeof(Rigidbody))]
public class UseTheForce : MonoBehaviour
{
[SerializeField] private Rigidbody _rb;
[SerializeField] private float _force = 10f;
[SerializeField] private float _upwardsForce = 2f;
[SerializeField] private float _torque = 50f;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
_rb.AddRelativeForce(0, _upwardsForce, _force, ForceMode.Impulse);
_rb.AddRelativeTorque(transform.right * _torque, ForceMode.Impulse);
}
}
Force Modes
Here are some definitions directly from the Unity documentation. Mostly you need to decide if you want to consider the mass of the object or ignore it, and choose your force mode depending on the desired behavior.
Impulse is great for something like void start, where you give a one time push to an object, while Force may be better suited for a rocket behavior running in Fixed Update.
Force: Add a continuous force to the rigidbody, using its mass.
Impulse: Add an instant force impulse to the rigidbody, using its mass.
Acceleration: Add a continuous acceleration to the rigidbody, ignoring its mass.
Velocity Change: Add an instant velocity change to the rigidbody, ignoring its mass.
Here is the punted cube, good for 3 points from 2 yards out, for the win! *crowd cheers*
I hope you enjoyed this introduction on using the force in Unity, and thanks for reading! Please join me in my next article where I discuss detecting and responding to collisions, as well as using the Add Explosion Force Unity method.