Issue with getting player to jump

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

Currently, I’m trying to use a piece of code to decrease the player’s y position to get them to jump, but I am running into a bit of an issue. With my current code (which is currently set up so that in the future I can add more mechanics) I’m using a state for a function, which doesn’t seem to work. However, I tested it with _physics_process(delta) and it worked then. I would like to keep the state machine, so I wanted to check here if there was a solution. Here’s the code:

extends KinematicBody2D

const ACCELERATION = 500
const MAX_SPEED = 80
const FRICTION = 500
const GRAVITY = 20
const FALL_SPEED = 200
const JUMP_FORCE = 1000

enum {
	MOVE,
	BLINK,
	SHOOT
}

var state = MOVE
var velocity = Vector2.ZERO

func _physics_process(delta):
	match state:
		MOVE:
			move_state(delta)
		
		BLINK:
			pass
		
		SHOOT:
			pass

func move_state(delta):
	var input_vector = Vector2.ZERO
	input_vector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
	input_vector = input_vector.normalized()
	
	if input_vector != Vector2.ZERO:
		velocity = velocity.move_toward(input_vector * MAX_SPEED, ACCELERATION * delta)
	else:
		velocity = velocity.move_toward(Vector2.ZERO, FRICTION * delta)
	
	velocity.y += GRAVITY
	if velocity.y > FALL_SPEED:
		velocity.y = FALL_SPEED
	
	if is_on_floor():
		if Input.is_action_just_pressed("jump"):
			velocity.y = -JUMP_FORCE
	
	velocity = move_and_slide(velocity)

Any assistance with this will be appreciated. Thank you.

:bust_in_silhouette: Reply From: timothybrentwood

Your velocity vector is accumulating velocity.y += GRAVITY worth of downwards force every frame, this adds up quickly and is hard to overcome with JUMP_FORCE.

if is_on_floor():
    velocity.y = 0
    if Input.is_action_just_pressed("jump"):
        velocity.y = -JUMP_FORCE
else:
    velocity.y += GRAVITY
    if velocity.y > FALL_SPEED:
        velocity.y = FALL_SPEED

velocity = move_and_slide(velocity)

no need to accumulate gravity when you’re on the floor, you’re already accounting for this with your use of FRICTION, which is probably the best way to do it imo.

I’ve tried that, but it still appears that there’s no change, jumping doesn’t work.

darkdestiny1010 | 2021-04-28 08:45

Found where I went wrong, needed to pass Vector2.UP in move_and_slide.

darkdestiny1010 | 2021-04-28 11:13

Ah yes, sorry for not realizing that. I’m glad you got it figured out!

timothybrentwood | 2021-04-28 11:56