generated at
Godot: WASDか上下左右Arrowで移動
まず、Godot: InputMapで WASD キーを up/left/down/right Actionとして登録する

Godot 3.5の書き方
KinematicBody2D のノードで、velocity を使って移動させる
押しっぱなしで加速するので、just系にするなど適宜変更する
gdscript.py
func _physics_process(delta): var input_dir = Vector2.ZERO if Input.is_action_pressed("ui_right"): input_dir.x += 1 if Input.is_action_pressed("ui_left"): input_dir.x -= 1 if Input.is_action_pressed("ui_down"): input_dir.y += 1 if Input.is_action_pressed("ui_up"): input_dir.y -= 1 input_dir = input_dir.normalized() move_and_slide(input_dir * speed)

Input.get_axis を使った書き方
gd
func _physics_process(delta): var input_dir = Vector2.ZERO input_dir.x = Input.get_axis("ui_left", "ui_right") input_dir.y = Input.get_axis("ui_up", "ui_down")

Input.get_vector を使った書き方
var velocity = Input.get_vector("move_left", "move_right", "move_forward", "move_back")

Input.get_action_strength() を使った書き方
gd
var x_mov = Input.get_action_strength("right") - Input.get_action_strength("left") var x_mov = Input.get_action_strength("down") - Input.get_action_strength("up") velocity = Vector2(x_mov, y_mov).normalized()

Grid-baseで動かせたい場合のレシピ
grid-base-move.py
extends Area2D var tile_size = 16 var inputs = {"right": Vector2.RIGHT, "left": Vector2.LEFT, "up": Vector2.UP, "down": Vector2.DOWN} func _unhandled_input(event): for dir in inputs.keys(): if event.is_action_pressed(dir): move(dir) func move(dir): position += inputs[dir] * tile_size
Godot 4.0からGodot 3.5にバックポートされた、Tween機能の改善を使ってTweenを使う場合は、move関数を以下にすればok
gd
func move(dir): create_tween().tween_property(self, "position", position + inputs[dir] * TILE_SIZE, 0.1)
ただし、この場合は グリッドからずれる可能性があるため、それを避けるにはTweenが完了するまで待たせたり、snap 処理が別途必要