How To Control Gravity in Unity
In today’s blog post, let’s talk about how we can control gravity in a video game.
Gravity in the Unity game engine
Unity has a built-in 3D physics engine that uses a global gravity setting affecting all objects with a Rigidbody component. By default, the gravity is set to -9.81 on the y-axis, which corresponds to Earth’s gravitational acceleration, pulling objects downward.
Unity gravity demonstration
Scene setup
I’ve set up a scene with a container and a portal attached to the lab’s ceiling.
Our objective is to make the portal pull the container upward when pressing the Space key. If we try to achieve this by changing the global gravity settings, it will affect all objects in the scene. Instead, we want to have a pulling force that only applies to the container.
Adding required components
First, I’m going to add a Rigidbody component to the container object and make sure that the Use Gravity property is checked.
Next, to constantly apply a force to the container, we need to add another component called Constant Force.
After that, let’s create a script called Gravity and attach it to the object because we’re going to apply the pulling force through code.
Scripting
First, let’s get a reference to the pulling force.
[SerializeField] private float _pullingForce;
I’m going to set it to 10 so it can outpull the default gravitational force in Unity (which is 9.81).
Next, let’s create a function called ApplyLocalForce that we can use to apply force to our container.
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ApplyLocalForce();
}
}
void ApplyLocalForce()
{
ConstantForce constantForce = GetComponent<ConstantForce>();
constantForce.force = new Vector3(0f, _pullingForce, 0f);
}
And here’s the result:
As you can see, the container gradually rises up when I press the Space key.