面朝移动方向
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 20 课,共 28 课。
英雄绘制时面朝右边,向左跑时也仍然面朝右边。
你看到的英雄都在它的 Look 子节点中。将节点的 scale.x 设为 -1,就能让该节点及其子节点左右镜像。因此,翻转 Look:
if direction > 0:
$Look.scale.x = 1
if direction < 0:
$Look.scale.x = -1不要翻转 CharacterBody2D 本身,这样它的碰撞形状就会保持原样。没有按下任何按键时,direction 的值为 0,两个 if 都不会运行。英雄会继续面朝上次移动的方向。
挑战
简单让英雄面朝移动的方向。
- 在
move_and_slide()之前,当direction > 0时,将$Look.scale.x设为1。 - 当
direction < 0时,将它设为-1。
按“开始”,然后向左移动:英雄会转向左边,并在停止后继续面朝左边。然后按“检查”。
亲手试试
extends CharacterBody2D
var speed = 220
var acceleration = 900
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 在线编辑器