This Action will add a force to a physics object in Unity – essentially, it will “push” an object in a given direction by a given amount.
- Unity Features
Step 1 – Create a script for the Action
Create a script Using as shown in the Scripting Basics Unity feature tutorial. Name the script PlayerMovement, and open it in Visual Studio.
For this example, we’ll create a very simple script called “TestForceAction”. You can name your script whatever you like, and can even use an existing script if you want to.
Step 2 – Get the Rigidbody or Rigidbody2D component
Adding force must be done using the Physics System. In Unity, and GameObject that will interact with the Physics System must have a Rigidbody or Rigidbody2D component. So, in order to use physics on this object, we’ll need to get this component.
In this example, we’ll be dealing with the Rigidbody2D component attached to the same object as the script. However, in your code, you can affect other GameObjects (such as ones you have collided with, or ones you have a reference to through an inspector field).
Step 3 – Use the AddForce() function on the Rigidbody to push the GameObject
AddForce() is a function on Rigidbody and Rigidbody2D that accepts a Vector as the parameter. A Vector represents a direction, and can be larger or smaller to represent a length or strength in that direction. This means that we can tell it what direction to push the object, and how strongly.
In this example, we’ll separate our Vector into a direction (the Normalise() function changes a Vector into just a direction, and doesn’t include strength anymore), and then we can multiply our direction by a strength number. This is useful for games because we usually want to have a strength decided separately ahead of time, then just choose direction during gameplay (for example, based on what buttons a player has pressed or where an enemy is).
In the example, we do all of this in the Update() function so that this will happen every frame. However, you can use a Condition to change when this occurs.
Step 4 – Attach your script to a GameObject
Attach your script to the object, as shown in the Scripting Basics Unity feature tutorial. If you are just doing this as a test, make sure the GameObject is visible, so we can see the effect of the script.
Step 5 – Attach a Rigidbody or Rigidbody2D to the same GameObject
Our script requires the Physics System in order to work, so you need to attach a Rigidbody or Rigidbody2D to the object as well.
Step 6 – Update Rigidbody or Rigidbody2D settings
You may want to turn off gravity and add some drag to your Rigidbody or Rigidbody2D, in order to more clearly see the results of your force.
Step 7 – Run the game and test
In the example, the object should move in a fixed direction every frame. Depending on your Rigidbody settings, the strength and direction of the force you applied, and any Conditions you used, your result may be different.