63 lines
1.8 KiB
GDScript
63 lines
1.8 KiB
GDScript
extends Node3D
|
|
@export var tree_scenes: Array[PackedScene] = []
|
|
@export var spawn_area_size: Vector2 = Vector2(2.0, 2.0)
|
|
@export var max_trees: int = 3
|
|
@export var min_distance: float = 0.5
|
|
var spawned_positions: Array[Vector3] = []
|
|
var parent_ground_tile: GroundTile
|
|
var rng: RandomClass = RandomClass.new()
|
|
|
|
func _ready():
|
|
parent_ground_tile = get_parent() as GroundTile
|
|
|
|
|
|
func spawn_trees_for_cell(cell_info: CellDataResource):
|
|
if not cell_info:
|
|
return
|
|
|
|
rng.set_seed(cell_info.cell_seed)
|
|
|
|
var tree_count = max(0, cell_info.trees.size())
|
|
spawn_trees(tree_count)
|
|
|
|
func spawn_trees(tree_count: int):
|
|
if tree_scenes.is_empty() or tree_count == 0:
|
|
return
|
|
|
|
# Clear existing trees WITHOUT queue_free()
|
|
for child in get_children():
|
|
child.free() # Immediate cleanup instead of queue_free()
|
|
spawned_positions.clear()
|
|
|
|
# Spawn new trees
|
|
var attempts = 0
|
|
var max_attempts = tree_count * 10
|
|
|
|
while spawned_positions.size() < tree_count and attempts < max_attempts:
|
|
var pos = get_random_position()
|
|
|
|
if is_position_valid(pos):
|
|
spawn_tree_at_position(pos)
|
|
spawned_positions.append(pos)
|
|
|
|
attempts += 1
|
|
|
|
# Rest of your functions stay the same...
|
|
func get_random_position() -> Vector3:
|
|
var x = rng.randf_range(-spawn_area_size.x / 2, spawn_area_size.x / 2)
|
|
var z = rng.randf_range(-spawn_area_size.y / 2, spawn_area_size.y / 2)
|
|
return Vector3(x, 0, z)
|
|
|
|
func is_position_valid(pos: Vector3) -> bool:
|
|
for existing_pos in spawned_positions:
|
|
if pos.distance_to(existing_pos) < min_distance:
|
|
return false
|
|
return true
|
|
|
|
func spawn_tree_at_position(pos: Vector3):
|
|
var random_index = rng.randi() % tree_scenes.size()
|
|
var random_tree_scene = tree_scenes[random_index]
|
|
var tree_instance = random_tree_scene.instantiate()
|
|
add_child(tree_instance)
|
|
tree_instance.position = pos
|
|
tree_instance.rotation.y = rng.randf() * TAU
|