Fire Bullets
Part of the Projects section of Coddy's Godot journey. Lesson 13 of 33.
E or Enter (the action key) fires a bullet. A bullet is a scene, bullet.tscn. Its own script flies it forward and removes it after 0.8 seconds. The ship makes one at its nose, points it the same way and adds it to the game:
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)Add the bullet to the ship's parent. A child moves and turns with its parent, so a bullet on the ship would swing with it.
is_action_just_pressed is true only on the frame the key goes down. Each press fires one bullet.
Challenge
Medium- Add
const BULLET = preload("res://bullet.tscn"). - When the
actionkey is just pressed, make a bullet 18 pixels in front of the ship, with the ship'srotation, and add it to the ship's parent.
Try it yourself
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
2Project: Asteroid Shooter
Turn the ShipFire the EnginePractice on your own: Godot playground