godot-first-2d-game/main.gd

65 lines
1.5 KiB
GDScript

extends Node
# Allows us to select the Mob scene.
@export var mob_scene: PackedScene
var score
# Called when the node enters the scene tree for the first time.
func _ready():
pass
func game_over():
$ScoreTimer.stop()
$MobTimer.stop()
$HUD.show_game_over()
$Music.stop()
$DeathSound.play()
func new_game():
score = 0
$Player.start($StartPosition.position)
$StartTimer.start()
$HUD.update_score(score)
$HUD.show_message("Get Ready")
# Get the mobs group (all Mob instances) and set them all to free.
get_tree().call_group("mobs", "queue_free")
$Music.play()
func _on_score_timer_timeout():
score += 1
$HUD.update_score(score)
func _on_start_timer_timeout():
$MobTimer.start()
$ScoreTimer.start()
func _on_mob_timer_timeout():
# Create a new Mob scene instance.
var mob = mob_scene.instantiate()
# Choose a random location on the path.
var mob_spawn_location = get_node("MobPath/MobSpawnLocation")
mob_spawn_location.progress_ratio = randf()
# Set mob's direction perpendicular to the path direction.
# Godot uses radians in angle functions.
# PI = 1/2 turn in radians.
var direction = mob_spawn_location.rotation + PI / 2
# Set mob's position to a random location.
mob.position = mob_spawn_location.position
# Add some randomness to the direction.
direction += randf_range(-PI / 4, PI / 4)
mob.rotation = direction
# Random velocity from 150 to 250.
var velocity = Vector2(randf_range(150.0, 250.0), 0.0)
mob.linear_velocity = velocity.rotated(direction)
# Spawn the mob.
add_child(mob)