Managing gravity

Godot Version

4.3

Question

I am trying to implement the whole about a 2D platformer…but i am getting strange effect concerning gravity: The character is levitating up forever…strange. Following there is the code:


extends CharacterBody2D

class_name PlayerController

const SPEED = 150.0
@export var HP =100.0
@export var JUMP_VELOCITY = -800.0
@export var jump_mult = 0.90
@export var falling_mult = 0.90
@export var falling_mul = 30
@export var electrified= false

@onready var gravity_sys = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var sprite: Sprite2D =$zombieSprite
@onready var animation_tree : AnimationTree = $AnimationTree

var speed_mult = 30.0
var direction:Vector2 = Vector2.ZERO
var on_air:bool = false

var jumping = false
var attack= false
var facing

func _ready():
	animation_tree.active = true
	
			
func _physics_process(delta):
	
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity_sys*delta
	
	#handle jump	
	if Input.is_action_just_pressed("Jump"): # and is_on_floor() :
		if is_on_floor():
			 jumping = true
	
	direction = Input.get_vector("go_left","go_right",'0','0') #moving only along horizontal axis
	move_and_slide()
	
		print('on floor and attacking !!')
		if not anim_Sprite2D.is_playing():
			print('NOT playing!!!')
			anim_Sprite2D.play("ATT")
		else:
			anim_Sprite2D.stop()
		
		
	if Glob.electricBlock == false:
		if  direction:
			velocity.x =direction.x*SPEED
		else:
			velocity.x = move_toward(velocity.x,0, SPEED)
			
	else:
		velocity.x = 0.0 

func update_animation():
	animation_tree.set("parameters/walk/blend_position",direction.x)

The gravity from the project settings is a positive number. (At least on 4.4.1). And you add it to the y-axis. Try subtracting it.

if not is_on_floor():
		velocity.y -= gravity_sys*delta

Just out of curiosity, why not let the physics engine handle gravity?
Edit
Just ignore that question. I always thought move_and_slide() would do that, but it does not. It just uses the property velocity (if set)

To follow the get_settings paradigma one could also get the direction from the project settings. Example code:

extends CharacterBody2D

@onready var gravity_sys = ProjectSettings.get_setting("physics/2d/default_gravity")
@onready var gravity_sys_direction: Vector2 = ProjectSettings.get_setting("physics/2d/default_gravity_vector")

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta: float) -> void:
	
	velocity.y += gravity_sys * gravity_sys_direction.y * delta
	velocity.x += gravity_sys * gravity_sys_direction.x * delta
	
	move_and_slide()

Or for ease of mind use the get_gravity function

which returns all gravity settings/influences, even those of Area2D objects. Which simplifies the code to:

func _physics_process(delta: float) -> void:	
	velocity += get_gravity() * delta
	
	move_and_slide()
1 Like