Changing gravity

Godot Version

4.2

Question

How do I switch the gravity in my Puzzle platformer?

Please reply

1 Like

Go to the project settings and locate Physics/2D/Default Gravity or simply search for gravity, right-click and select “Copy property path”, then write the code as follows:

# "physics/2d/default_gravity" is what you have copied
ProjectSettings.set_setting("physics/2d/default_gravity", -980)

Or you can change the gravity direction:

# Set it to "Vector2(0, 1)" will make gravity to the right
ProjectSettings.set_setting("physics/2d/default_gravity_vector", Vector2(0, 1))

Basically, you copy the setting’s path and use it in the ProjectSettings.set_setting() method. This is how you change any setting in the code.

Thank you. Please tell me the other directions, It would be really helpful. :+1: :grinning: :godot:

Since Vector2 has an x and a y, and positive x is pointing right, and positive y is pointing down, you can combine these together to make any direction.

For example, we want gravity to the left, then we need x set to -1, and 0 for y, the result is Vector2(-1, 0). Be careful about this, for this changes the direction but also the gravity scale.

And I just noticed in the documentation that how to change physics/2d/default_gravity_vector at runtime.

This is the following section:

Note: This property is only read when the project starts. To change the default gravity vector at runtime, use the following code sample:

# Set the default gravity direction to `Vector2(0, 1)`.
PhysicsServer2D.area_set_param(get_viewport().find_world_2d().space, PhysicsServer2D.AREA_PARAM_GRAVITY_VECTOR, Vector2.DOWN)

This reminds us to be careful about descriptions in the docs instead of always guessing around and lost.

does this mean that if I change the gravity direction, and its stronger than I expected, will I be able to use decimals?