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") * speedDo 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
EasyLet the hero run while it falls and jumps.
- Above
move_and_slide(), setvelocity.xtoInput.get_axis("move_left", "move_right")timesspeed. - Leave
velocity.yto 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
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground