What's missing in my gravity code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Halfpixel


I’m new to programming and to Godot.
My code for my player is working fine including gravity “velocity.y += GRAVITY”

However for an enemy, gravity is not working the same.
The y values 50 each below is simply for me to understand where is the problem, the enemy simply goes on a straight line when I would like gravity to pull further down.
I’m guessing there is a problem with the line “velocity.y += GRAVITY”, I don’t know.

Here is the code:

(the commented part probably has no connection, ignore)

extends KinematicBody2D

const GRAVITY = 50
export var jump_height = -50
export var jump_reach = -150
var velocity = Vector2()

#var jumping_enabled = false

func _physics_process(delta):
velocity.y = jump_height
velocity.x = jump_reach
velocity.y += GRAVITY

# if jumping_enabled == true:
# velocity.y = jump_height
# velocity.x = jump_reach
# velocity.y += GRAVITY

velocity = move_and_slide(velocity)

#func _on_Area2D_body_entered(body):
# jumping_enabled = true

Gravity is 50 and jump -50 so don’t they cancel each other.

magicalogic | 2021-06-23 08:27

Yes you’re right, they cancel each other out.
What I need is to simulate a jump.
I have achieved this (jump) in another scene with jump -750 and gravity 35 (another character).
In this scene, when I change the jump & gravity values I’m getting a linear upwards or downwards depending on jump and gravity values.
Which is why I changed them to equal each other wanting to find out if it’s a problem with “velocity.y += GRAVITY”.
I was assuming “velocity.y += GRAVITY” is different than “velocity.y = jump_height” where the former keeps accumulating gravity value to velocity instead of simply adding, seems they are cancelling each other out.
My idea was player enters area2d and enemy jumps forward.
Any idea what’s missing from the code to be able mimic a jump?

Halfpixel | 2021-06-23 10:14

:bust_in_silhouette: Reply From: lewis glasgow
var grav = 0
var grav_strength = 1
var jump_height = -10

func _process(delta):
	var vel = Vector2()
	if is_on_floor():
		vel.y = grav_strength
		grav = 0
		#vel.y has to be vel.y > 0 so is_on_floor() can be true
		grav += grav_strength

	if Input.is_action_pressed("jump") && is_on_floor():
		grav = jump_height
	#jump code has to be after fall code so grav can be overwritten

	vel.y += grav