Menu
CoddyTech

英雄:回到起点

本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 27 课,共 28 课。

如果英雄掉进坑里,就应该回到起点。

在 _ready() 中用一个变量保存起点,_ready() 会在英雄移动前运行:

var start_position = Vector2()

func _ready():
	start_position = position

在 move_and_slide() 后,检查英雄是否掉到了 360 像素高的屏幕下方。让它回到起点,并重置它的速度,这样它就不会继续下落着落地:

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

挑战

中等

英雄掉进坑里时,让它回到起点。

  1. 添加 var start_position = Vector2(),并在新的 _ready() 中将它设为 position。
  2. 在 move_and_slide() 之后,当 position.y > 400 时,将 position 设为 start_position,并将 velocity 设为 Vector2(0, 0)。

按“开始”并掉进坑里:英雄会回到起点。然后点击“检查”。

亲手试试

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

输入与移动中的所有课

自己练习: Godot 在线编辑器