英雄:面向前进方向
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 26 课,共 28 课。
角色向左跑时仍然面朝右。让它的 Look 节点按按键指示的方向翻转:
if direction > 0:
$Look.scale.x = 1
if direction < 0:
$Look.scale.x = -1在设置好 direction 后添加这些代码行。没有按住任何按键时,两个 if 都不会运行,因此角色会保持上次的朝向。
挑战
简单让角色面朝移动的方向。
- 在
move_and_slide()之前,当direction > 0时,将$Look.scale.x设为1。 - 当
direction < 0时,将它设为-1。
按“开始”,然后向左移动:角色会转向左边,并在你停下时继续面朝左边。然后点击“检查”。
亲手试试
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)
move_and_slide()
输入与移动中的所有课
自己练习: Godot 在线编辑器