单个轴
本课属于 Coddy Godot 学习旅程的“输入与移动”单元。第 3 课,共 28 课。
左和右是一条线(轴)的两个端点。Input.get_axis()会检查两个动作,并返回一个数字:
- 按住第一个动作(左)时返回
-1 - 按住第二个动作(右)时返回
1 - 两个动作都没有按住,或同时按住时返回
0
将这个数字乘以速度,英雄就会朝正确的方向移动,无需使用 if:
var speed = 300
func _process(delta):
var direction = Input.get_axis("move_left", "move_right")
position.x += direction * speed * delta当 direction 为 -1 时,x 会变小,英雄向左移动。当它为 0 时,英雄会停在原地。
挑战
简单用一行输入让英雄左右移动。
- 在
_process()中,将Input.get_axis("move_left", "move_right")存入var direction。 - 让
position.x每秒移动direction * speed。
按“开始”:方向键会让英雄以每秒 300 像素的速度移动,同时按下两个方向键会让英雄停在原地。然后按“检查”。
亲手试试
extends Node2D
var speed = 300
func _process(delta):
pass
输入与移动中的所有课
自己练习: Godot 在线编辑器