Menu
CoddyTech

Face the Way You Move

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

The hero is drawn facing right, and it still faces right when it runs left.

Everything you see of the hero is in its Look child. A scale.x of -1 mirrors a node and its children left to right. So flip Look:

if direction > 0:
	$Look.scale.x = 1
if direction < 0:
	$Look.scale.x = -1

Do not flip the CharacterBody2D itself, so its collision shape stays as it is. With no key held, direction is 0 and neither if runs. The hero keeps facing the way it last went.

challenge icon

Challenge

Easy

Make the hero face the way it runs.

  1. Before move_and_slide(), set $Look.scale.x to 1 when direction > 0.
  2. Set it to -1 when direction < 0.

Press Play and run left: the hero turns left and keeps facing left when you stop. Then Check.

Try it yourself

extends CharacterBody2D

var speed = 220
var acceleration = 900
var friction = 2400
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
	var direction = Input.get_axis("move_left", "move_right")
	if direction == 0:
		velocity.x = move_toward(velocity.x, 0, friction * delta)
	else:
		velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)
	move_and_slide()

All lessons in Input and Movement

Practice on your own: Godot playground