2023-09-30 18:16:14 +00:00
|
|
|
extends Node2D
|
|
|
|
class_name Spawner
|
2023-09-30 23:33:54 +00:00
|
|
|
|
|
|
|
|
2023-09-30 18:16:14 +00:00
|
|
|
@export var scene: PackedScene
|
2023-09-30 23:33:54 +00:00
|
|
|
|
2023-09-30 23:56:54 +00:00
|
|
|
var buffer: int = 0
|
|
|
|
@export var buffer_cap: int
|
|
|
|
|
2023-09-30 23:58:46 +00:00
|
|
|
@onready var area: Area2D = $Area
|
2023-10-01 00:18:08 +00:00
|
|
|
|
2023-10-01 00:27:49 +00:00
|
|
|
@export var spawn_position_range_x: float
|
|
|
|
@export_range(0, 90) var spawn_rotation_range: float
|
2023-10-01 00:18:08 +00:00
|
|
|
@onready var rng: RandomNumberGenerator = RandomNumberGenerator.new()
|
2023-09-30 23:58:46 +00:00
|
|
|
|
2023-10-01 00:38:27 +00:00
|
|
|
@export_flags_2d_physics var overlapping_bodies_collision_mask: int
|
|
|
|
@export_range(0, 16) var overlapping_body_count_limit: int
|
|
|
|
|
2023-10-01 00:57:06 +00:00
|
|
|
signal spawned(what: Node2D)
|
2023-10-01 00:41:39 +00:00
|
|
|
|
2023-09-30 18:16:14 +00:00
|
|
|
|
|
|
|
func spawn():
|
2023-09-30 23:59:28 +00:00
|
|
|
buffer += 1
|
|
|
|
if buffer > buffer_cap:
|
|
|
|
buffer = buffer_cap
|
2023-09-30 23:56:54 +00:00
|
|
|
|
2023-10-01 00:38:27 +00:00
|
|
|
func _count_overlapping_bodies() -> int:
|
|
|
|
var overlapping_bodies = area.get_overlapping_bodies()
|
|
|
|
var overlapping_body_count = 0
|
|
|
|
for overlapping_body in overlapping_bodies:
|
2023-10-01 00:47:54 +00:00
|
|
|
if overlapping_body.collision_layer & overlapping_bodies_collision_mask:
|
2023-10-01 00:38:27 +00:00
|
|
|
overlapping_body_count += 1
|
|
|
|
return overlapping_body_count
|
|
|
|
|
2023-09-30 23:56:54 +00:00
|
|
|
|
2023-10-01 00:18:08 +00:00
|
|
|
func _select_spawn_position() -> Vector2:
|
2023-10-01 00:27:49 +00:00
|
|
|
return Vector2(rng.randf_range(-spawn_position_range_x, +spawn_position_range_x), 0)
|
|
|
|
|
|
|
|
func _select_spawn_rotation() -> float:
|
|
|
|
return rng.randf_range(-spawn_rotation_range, spawn_rotation_range)
|
2023-10-01 00:18:08 +00:00
|
|
|
|
|
|
|
func _do_spawn():
|
2023-10-01 00:38:27 +00:00
|
|
|
if _count_overlapping_bodies() > overlapping_body_count_limit:
|
|
|
|
return
|
2023-10-01 00:18:08 +00:00
|
|
|
var scene_instant = scene.instantiate()
|
2023-10-01 00:27:49 +00:00
|
|
|
scene_instant.position = _select_spawn_position()
|
|
|
|
scene_instant.rotation_degrees = _select_spawn_rotation()
|
2023-10-01 00:18:08 +00:00
|
|
|
add_child(scene_instant)
|
2023-10-01 00:41:39 +00:00
|
|
|
emit_signal("spawned", scene_instant)
|
2023-10-01 00:18:08 +00:00
|
|
|
buffer -= 1
|
|
|
|
|
|
|
|
|
2023-09-30 23:56:54 +00:00
|
|
|
func _physics_process(_delta):
|
|
|
|
if buffer > 0:
|
2023-10-01 00:18:08 +00:00
|
|
|
_do_spawn()
|