Jump doesn't work when I implement walking

Godot Version

4.3

Question

Hello, this is my first Godot project. I’m coming from Roblox Studio.

I am trying to make a 2D platformer game. I don’t know why my character doesn’t want to jump when I add my code for walking. Here’s the code:

extends CharacterBody2D


const SPEED = 250.0
# var speed_multiplier = 1.0
const JUMP_VELOCITY = 400.0
# var jump_velocity_multiplier = 1.0


func _input(event) -> void:
	if event.is_action_pressed("ui_accept") and is_on_floor():
		velocity += (Vector2.UP + get_floor_normal()) / 2 * JUMP_VELOCITY

func _physics_process(delta) -> void:
	# Gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta  

	# Walking. If I delete this part, the jumping works as intended.
	var walk_input = Input.get_axis("ui_left", "ui_right")
	if is_on_floor():
		velocity = get_floor_normal().rotated(deg_to_rad(90)) * walk_input * SPEED

	move_and_slide()

Thanks in advance!

1 Like

because you set the velocity to a new value when you walk which overwrites the old jump value. You can fix this by putting the input_event in the _physics_process:

func _physics_process(delta) -> void:
	# Gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta  

	# Walking. If I delete this part, the jumping works as intended.
	var walk_input = Input.get_axis("ui_left", "ui_right")
	if is_on_floor():
		velocity = get_floor_normal().rotated(deg_to_rad(90)) * walk_input * SPEED

    if Input.is_action_pressed("ui_accept") and is_on_floor():
		velocity += (Vector2.UP + get_floor_normal()) / 2 * JUMP_VELOCITY

	move_and_slide()
2 Likes

In Seas of Reverence, I maintain 3 different motion vectors (vertical motion, horizontal motion, and depth motion) and combine them on each frame:

velocity = vecX + vecY + vecZ

It makes motion control significantly easier than trying to maintain the velocity vector directly.

For 2D, you would do away with the Z vector.

2 Likes

how would that work with slopes? i use velocity = get_floor_normal().rotated(deg_to_rad(90)) * walk_input * SPEED for slopes.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.