Menu
CoddyTech

平衡的斜向移动

本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 11 课,共 28 课。

上一课中的英雄沿对角线移动时太快了。向上和向右移动时,速度为 Vector2(200, -200)。这个向量的长度约为 283 像素,而不是 200。

.normalized() 会保留向量的方向,并将其长度设为恰好 1。再乘以速度:

var direction = Vector2(Input.get_axis("move_left", "move_right"), Input.get_axis("move_up", "move_down"))
velocity = direction.normalized() * speed
move_and_slide()

这样,英雄沿任何方向移动的速度都是每秒 200 像素。Vector2(0, 0) 归一化后仍为零,因此英雄会停下。

Input.get_vector() 返回的方向向量长度最大为 1。使用 velocity = Input.get_vector("move_left", "move_right", "move_up", "move_down") * speed,沿对角线移动时也同样公平。

challenge icon

挑战

中等

让英雄斜向移动时也一样快。

  1. 将两个轴放进一个 Vector2 中:var direction = Vector2(Input.get_axis("move_left", "move_right"), Input.get_axis("move_up", "move_down"))。
  2. 用 direction.normalized() * speed 设置 velocity,替换原来的两行 velocity。

按下“开始”:英雄向任意方向移动的速度都是每秒 200 像素,斜向也一样。然后按“检查”。

亲手试试

extends CharacterBody2D

var speed = 200

func _physics_process(delta):
	velocity.x = Input.get_axis("move_left", "move_right") * speed
	velocity.y = Input.get_axis("move_up", "move_down") * speed
	move_and_slide()
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

输入与移动中的所有课

自己练习: Godot 在线编辑器