Fair Diagonals
Part of the Input and Movement section of Coddy's Godot journey. Lesson 11 of 28.
The last lesson's hero is too fast on a diagonal. Up and right give a velocity of Vector2(200, -200). That vector is about 283 pixels long, not 200.
.normalized() keeps a vector's direction and makes it exactly 1 long. Multiply that by the speed:
var direction = Vector2(Input.get_axis("move_left", "move_right"), Input.get_axis("move_up", "move_down"))
velocity = direction.normalized() * speed
move_and_slide()Every direction then moves at 200 pixels per second. Vector2(0, 0) stays zero when normalized, so the hero stops.
Input.get_vector() already returns a direction at most 1 long. velocity = Input.get_vector("move_left", "move_right", "move_up", "move_down") * speed is fair on diagonals too.
Challenge
MediumMake the hero walk at 200 pixels per second in every direction, diagonals too. Use .normalized() on a Vector2 direction, or use Input.get_vector().
Try it yourself
extends CharacterBody2D
var speed = 200
func _physics_process(delta):
velocity.x = Input.get_axis("move_left", "move_right") * speed
velocity.y = Input.get_axis("move_up", "move_down") * speed
move_and_slide()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground