@Ebenezer said:
Hello guy. I am making a game in Godot but I program my player to always be on the ground because of gravity what of I want my player to not be affected by gravity and fly and can later come to the ground and be affected by gravity again, what should I do, should I use a variable like this:
Grav_afec = true.
Please tell me how to program it.
It is hard to say how to program it because it depends on how you are calculating gravity, and how your code is setup. That said, I have outlined a couple different methods of disabling gravity based on the node in use, so hopefully one of them will work for your project.
Also, as you have guessed, you almost certainly will need a variable for tracking whether you should add gravity in most cases. You can get away without a additional variable if you are using a RigidBody/RigidBody2D node, but even then the code is a little cleaner if you use a variable just for tracking the gravity state.
If you are using a RigidBody or RigidBody2D node, you can change the gravity_scale variable to change how strong gravity is for the RigidBody node. While I do not have any code handy, something like this in theory should do it:
extends RigidBody2D
var use_gravity = true;
func _ready():
pass
func change_gravity(grav_state):
use_gravity = grav_state;
if (use_gravity == true):
gravity_scale = 1;
else:
gravity_scale = 0;
func _process(delta):
if (Input.is_action_just_pressed("ui_enter")):
change_gravity(!use_gravity)
If you are using a KinematicBody or KinematicBody2D node, then you'll need to just stop applying gravity when you no longer need/want it. Assuming you are using the code from the Godot documentation on making a Kinematic Character 2D, then you'll just need something like this:
extends KinematicBody2D
const GRAVITY = 200.0
const WALK_SPEED = 200
var velocity = Vector2()
var use_gravity = true
func _physics_process(delta):
if (use_gravity == true):
velocity.y += delta * GRAVITY
if Input.is_action_pressed("ui_left"):
velocity.x = -WALK_SPEED
elif Input.is_action_pressed("ui_right"):
velocity.x = WALK_SPEED
else:
velocity.x = 0
if Input.is_action_just_pressed("ui_enter"):
use_gravity = !use_gravity;
move_and_slide(velocity, Vector2(0, -1))
If you are using a different node setup, like using a Area or Area2D as the primary collision method, then you'll likely need code similar to the KinematicBody/KinematicBody2D setup above, where you only apply gravity when a certain condition is true.
Hopefully this helps :smile: