【Godot2D】弾丸発射機能の追加
前回作成したただ移動するだけのオブジェクト(▶︎こちら)に、弾丸を発射する機能を追加してみました。
こういう感じ↓
参考にした動画はこちら↓
https://www.youtube.com/watch?v=oOIDR1KlDG0
弾丸素材はこちら(無料)を使わせていただきました↓
https://wenrexa.itch.io/laser2020
操作コマンド
「プロジェクト管理>インプットマップ」から、”attack"コマンドを追加。
ファイル
今回追加したのは、シーン「bullet.tscn」「gun.tscn」とスクリプト「bullet.gd」「gun.gd」
シーン
bullet.tscn
gun.tscn
スクリプト
bullet.gd
メモ
queue_free()・・・(次フレームで)ノードを削除
_ready ・・・弾丸が3秒で消えるようにする設定。
get_tree().create_timer(3) → 3秒のタイマーを作成
await ... .timeout → タイマーが終了するまで待機
queue_free() → 弾を削除(シーンツリーから消す)
set_direction ・・・弾の飛ぶ方向をセット。
bulletDirection を direction に代入。
rotation_degrees を変更し、弾の見た目を進行方向に向ける。
angle_to_point(global_position + direction) → 方向ベクトルの角度(ラジアン)を取得。
rad_to_deg(...) → ラジアンを度(°)に変換
_physics_process
毎フレーム global_position を更新。弾丸を一定速度で移動させる設定。
_on_body_entered ・・・今回は使わない。拡張用。
Area2D の シグナル body_entered に接続された関数。
弾が何かに当たったとき、この関数が呼ばれる。
if body.is_in_group("enemies"): 敵グループなら処理を実行。
body.get_damage(damage): 敵にダメージを与える。
queue_free(): 弾を削除。
gun.gd
メモ
_ready ・・・shoot_speed_timer の発射間隔の設定。
shoot ・・・弾を発射する処理。
canShoot が true の場合、弾を発射、canShoot を false に設定して、弾が発射できない状態にする。
shoot_speed_timer.start() によって、発射の間隔を設定してタイマーを開始。
BULLET.instantiate() で bullet.tscn シーンから弾のインスタンスを作成。
bulletNode.set_direction(bulletDirection) で弾の向きを設定。
get_tree().root.add_child(bulletNode) で弾をシーンに追加。
bulletNode.global_position = marker_2d.global_position で、弾の発射位置を Marker2D の位置に設定。
_on_shoot_speed_timer_timeout
・・・タイマーが終了したときに呼ばれ、canShoot を true に戻す。弾が再度発射可能に。
setup_direction ・・・弾の発射方向の設定。
direction.x や direction.y に基づいて発射の向きやスケール(反転)を変更。
direction.x > 0 → 右向き
direction.x < 0 → 左向き(scale.x = -1 によって反転)
direction.y < 0 → 上向き(rotation_degrees = -90)
direction.y > 0 → 下向き(rotation_degrees = 90)
前回作ったシーンに追加
player.tscnに「子シーンをインスタンス化」でgun.tscnを追加。
さらにplayer.gdに以下のスクリプトを追加。
4 @onready var gun: Node2D = $Gun
9 if Input.is_action_pressed("attack"):
10 gun.shoot()
16 if direction != Vector2.ZERO:
17 gun.setup_direction(direction)