Menu
CoddyTech

左右移动

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

一个 if 检查一个动作。要向两个方向移动,请为另一个动作再添加一个 if:

func _process(delta):
	if Input.is_action_pressed("move_right"):
		position.x += 200 * delta
	if Input.is_action_pressed("move_left"):
		position.x -= 200 * delta

每一帧,Godot 都会运行这两项检查。每项检查只会在按住对应按键时移动英雄。

同时按住两个按键时,两行代码会在同一帧运行。一行每秒增加 200 像素,另一行则减去这些像素,所以英雄会停在原地。

challenge icon

挑战

简单

让主角也向左走。

  1. 在第一个 if 下面,再添加一个 if,检查是否按下了 "move_left"。
  2. 在其中让主角以每秒 200 像素的速度向左移动。

按下“开始”并按住左箭头键:主角会向左走。然后点击“检查”。

亲手试试

extends Node2D

func _process(delta):
	if Input.is_action_pressed("move_right"):
		position.x += 200 * delta

输入与移动中的所有课

自己练习: Godot 在线编辑器