英雄:到达平台边缘
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 28 课,共 28 课。
目标是带有旗帜的高台。英雄带着一个 Banner,这是一个隐藏的 Label,上面写着 You made it!
英雄在地面上时,position.y 是 278。在台阶上时是 218,在高台上时是 158。因此,英雄只有在站在地面上且 position.y 小于 170 时,才算站在高台上:
if is_on_floor() and position.y < 170:
$Banner.visible = trueis_on_floor() 这一部分很重要。从地面起跳时,英雄也会短暂地经过 170,但那时他还在空中。
要获胜,先跳过坑,再跳上台阶,最后跳上高台。
挑战
中等英雄到达平台边缘时,显示横幅。
- 在
_physics_process()的末尾添加一个if:is_on_floor()且position.y < 170。 - 在其中显示
$Banner。
按“开始”并爬到平台边缘:横幅上会显示 You made it!。然后按“检查”。
亲手试试
extends CharacterBody2D
var speed = 220
var acceleration = 1200
var friction = 2400
var gravity = 1000
var jump_velocity = -500
var start_position = Vector2()
func _ready():
start_position = position
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()
if position.y > 400:
position = start_position
velocity = Vector2(0, 0)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
输入与移动中的所有课
自己练习: Godot 在线编辑器