Fire Bullets
Part of the Projects section of Coddy's Godot journey. Lesson 14 of 36.
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
MediumFire a bullet with E.
- Add
const BULLET = preload("res://bullet.tscn"). - When
actionis just pressed, make a bullet 18 pixels in front of the ship, with the ship'srotation. - Add it to the ship's parent with
get_parent().add_child(bullet).
Press Play and press E: a bullet flies from the nose. Then Check.
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
All lessons in Projects
Practice on your own: Godot playground