Hero: Back to the Start
Part of the Input and Movement section of Coddy's Godot journey. Lesson 27 of 28.
If the hero falls into the pit, it should go back to the start.
Store the start in a variable in _ready(), which runs before the hero moves:
var start_position = Vector2()
func _ready():
start_position = positionAfter move_and_slide(), check whether the hero fell below the 360 pixel screen. Put it back, and reset its velocity so it does not arrive still falling:
if position.y > 400:
position = start_position
velocity = Vector2(0, 0)Challenge
MediumSend the hero back to the start when it falls into the pit.
- Add
var start_position = Vector2(), and in a new_ready()set it toposition. - After
move_and_slide(), whenposition.y > 400, setpositiontostart_positionandvelocitytoVector2(0, 0).
Press Play and fall into the pit: the hero comes back at the start. Then Check.
Try it yourself
extends CharacterBody2D
var speed = 220
var acceleration = 1200
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)
if direction > 0:
$Look.scale.x = 1
if direction < 0:
$Look.scale.x = -1
move_and_slide()
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground