Menu
CoddyTech

Héroe: volver al inicio

Parte de la sección Entrada y movimiento del Journey de Godot de Coddy. Lección 27 de 28.

Si el héroe cae en el foso, debería volver al inicio.

Guarda el inicio en una variable en _ready(), que se ejecuta antes de que el héroe se mueva:

var start_position = Vector2()

func _ready():
	start_position = position

Después de move_and_slide(), comprueba si el héroe cayó por debajo de la pantalla de 360 píxeles. Devuélvelo al inicio y restablece su velocidad para que no llegue todavía cayendo:

if position.y > 400:
	position = start_position
	velocity = Vector2(0, 0)
challenge icon

Desafío

Intermedio

Devuelve al héroe al inicio cuando caiga en el foso.

  1. Añade var start_position = Vector2() y, en un nuevo _ready(), asígnale position.
  2. Después de move_and_slide(), cuando position.y > 400, asigna start_position a position y Vector2(0, 0) a velocity.

Pulsa «Jugar» y cae en el foso: el héroe vuelve al inicio. Después, pulsa «Comprobar».

Pruébalo tú mismo

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()

Todas las lecciones de Entrada y movimiento

Practica por tu cuenta: Playground de Godot