使用速度行走
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 8 课,共 28 课。
要用按键移动,每个物理帧都通过 Input.get_axis() 设置速度,然后移动:
var speed = 200
func _physics_process(delta):
velocity.x = Input.get_axis("move_left", "move_right") * speed
move_and_slide()按住右方向键时,velocity.x 的值为 200。按住左方向键时,值为 -200。什么都不按时,值为 0,所以松开按键后,英雄就会停下来。
使用 Node2D 时,你写的是 position.x += direction * speed * delta。使用物理体时,velocity 本身就是速度。再乘以 delta 会让英雄慢 60 倍。
挑战
简单让英雄用速度向左和向右行走。
- 在
move_and_slide()上方,将velocity.x设置为Input.get_axis("move_left", "move_right")乘以speed。 - 不要用
delta:move_and_slide()会替你应用它。
按“开始”并按住一个方向键:英雄会以每秒 200 像素的速度行走,松开按键后就会停下。然后点击“检查”。
亲手试试
extends CharacterBody2D
var speed = 200
func _physics_process(delta):
move_and_slide()
输入与移动中的所有课
自己练习: Godot 在线编辑器