墙壁会挡住你
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 9 课,共 28 课。
墙壁和柱子都是 StaticBody2D 节点。静态物体不会移动。每个物体都有一个 CollisionShape2D 表示它的实体形状,还有一个 ColorRect 用来绘制它。
只有 move_and_slide() 会检测墙壁。更改 position 会移动物体而不进行检测,所以物体会穿过墙壁:
position.x += direction * speed * delta # 可以穿过墙壁
velocity.x = direction * speed # 会被墙壁挡住
move_and_slide()# 后面的文本是注释。Godot 会跳过它。
物体以一定角度撞上墙壁时,会保留沿墙移动的部分。它会滑动,而不是卡住,这就是 move_and_slide() 这个名称的由来。
挑战
简单让墙壁挡住英雄。
- 将
position.x这一行替换为一行代码,将velocity.x设置为direction * speed,不要使用delta。 - 在它下面调用
move_and_slide()。
按下“开始”,向两个方向行走:柱子和墙壁都会挡住英雄。然后点击“检查”。
亲手试试
extends CharacterBody2D
var speed = 200
func _physics_process(delta):
var direction = Input.get_axis("move_left", "move_right")
position.x += direction * speed * delta
输入与移动中的所有课
自己练习: Godot 在线编辑器