
GODOT DOCS キャラを操作する
前回は、キャラを回転させました。
今回は前回のスクリプトをベースに、キャラの操作について学びます。
今日のハイライト

キャラを操作する
スクリプトを修正する
func _process(delta: float) -> void:
# コメントアウト
#rotation += angular_speed * delta
#var velocity = Vector2.UP.rotated(rotation) * speed # キャラの角速度を定義
#position += velocity * delta # 毎フレーム角速度で移動させる
Rotation以下を差し替えるようなので、後で戻せるようにコメントアウトしておきます。
コメントアウトしたい行を選択して「CTRL+K」すると、先頭に#がついてコメントアウトします。
左右キーでキャラを回転
以下、プログラムを追記します。
func _process(delta: float) -> void:
# コメントアウト
#rotation += angular_speed * delta
#var velocity = Vector2.UP.rotated(rotation) * speed # キャラの角速度を定義
#position += velocity * delta # 毎フレーム角速度で移動させる
var direction = 0 # 方向
if Input.is_action_pressed("ui_left"): # 左矢印を押したら左回転
direction = -1
if Input.is_action_pressed("ui_right"): # 右矢印を押したら右回転
direction = 1
rotation += angular_speed * direction * delta # キャラの向きを制御
左右の矢印キーでキャラを回転できました。

上キーで前進
func _process(delta: float) -> void:
#rotation += angular_speed * delta
#var velocity = Vector2.UP.rotated(rotation) * speed # キャラの角速度を定義
#position += velocity * delta # 毎フレーム角速度で移動させる
var direction = 0
if Input.is_action_pressed("ui_left"):
direction = -1
if Input.is_action_pressed("ui_right"):
direction = 1
rotation += angular_speed * direction * delta
var velocity = Vector2.ZERO
if Input.is_action_pressed("ui_up"):
velocity = Vector2.UP.rotated(rotation) * speed
position += velocity * delta
上で前進して左右で回転します。
ここで、positionの前に、以下を追加して、下で後退するようにしてみました。
if Input.is_action_pressed("ui_down"):
velocity = Vector2.DOWN.rotated(rotation) * speed
無事、前進、後退、左右回転ができるようになりました。
戦車ゲームできそうです。

GODOT DOCSは学習効果あり!
全然、バグらなくてサクサク進むのでストレスフリー!
機能の理解もしやすいし、おススメの学習方法かも。
いつもは、いきなりゲーム作りながら覚えるけど、こっちはいいな。
皆さんも作ってみてはいかがでしょう。
お役に立てれば幸いです。