Menu
CoddyTech

Run and Jump

Part of the Input and Movement section of Coddy's Godot journey. Lesson 15 of 28.

Running changes only velocity.x. Gravity and the jump change only velocity.y. So set the two halves apart:

velocity.x = Input.get_axis("move_left", "move_right") * speed

Do not set the whole velocity, like this:

velocity = Vector2(Input.get_axis("move_left", "move_right") * speed, 0)

That line sets velocity.y to 0 every frame. It erases the falling speed and the jump, so the hero floats.

challenge icon

Challenge

Easy

Let the hero run while it falls and jumps.

  1. Above move_and_slide(), set velocity.x to Input.get_axis("move_left", "move_right") times speed.
  2. Leave velocity.y to gravity and the jump.

Press Play: the hero runs at 220 pixels per second and can jump up and right. Then Check.

Try it yourself

extends CharacterBody2D

var speed = 220
var gravity = 1000
var jump_velocity = -500

func _physics_process(delta):
	velocity.y += gravity * delta
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = jump_velocity
	move_and_slide()

All lessons in Input and Movement

Practice on your own: Godot playground