弾を撃つ
CoddyのGodotジャーニー「プロジェクト」セクションの一部。レッスン 14/36。
EまたはEnter(actionキー)を押すと弾を発射します。弾はシーンbullet.tscnです。弾自身のスクリプトが前方へ飛ばし、0.8秒後に削除します。船は機首の位置に弾を生成し、船と同じ向きにして、ゲームに追加します。
if Input.is_action_just_pressed("action"):
var bullet = BULLET.instantiate()
bullet.position = position + Vector2.UP.rotated(rotation) * 18
bullet.rotation = rotation
get_parent().add_child(bullet)弾を船の親に追加します。子は親と一緒に移動して向きを変えるため、弾を船の子にすると、船と一緒に振り回されてしまいます。
is_action_just_pressedがtrueになるのは、キーを押したフレームだけです。押すたびに弾を1発発射します。
チャレンジ
中級Eキーで弾を発射します。
const BULLET = preload("res://bullet.tscn")を追加します。actionが押された直後に、船の前方18ピクセルの位置に、船のrotationと同じ回転で弾を作成します。get_parent().add_child(bullet)で船の親に追加します。
「プレイ」を押してからEを押すと、船首から弾が飛びます。その後、「確認」を押します。
自分で試してみよう
extends CharacterBody2D
const TURN_SPEED = 4.0
const THRUST = 300
func _physics_process(delta):
rotation += Input.get_axis("move_left", "move_right") * TURN_SPEED * delta
if Input.is_action_pressed("move_up"):
velocity += Vector2.UP.rotated(rotation) * THRUST * delta
$Flame.visible = Input.is_action_pressed("move_up")
position += velocity * delta
if position.x < 0:
position.x += 640
if position.x > 640:
position.x -= 640
if position.y < 0:
position.y += 360
if position.y > 360:
position.y -= 360
プロジェクトのすべてのレッスン
自分で練習してみよう: Godotプレイグラウンド