nature-sim/Entities/GroundTile/scripts/trees.gd
Dan Baker 57602adddb Removes unused variable
Removes the unused 'rng' variable from the trees script.
This simplifies the code and reduces unnecessary memory allocation.
2025-06-26 15:27:56 +01:00

63 lines
1.9 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
func _ready():
parent_ground_tile = get_parent() as GroundTile
func spawn_trees_for_cell(cell_info: CellDataResource):
if not cell_info:
return
# Use parent's RNG instead of creating new one
if not parent_ground_tile or not parent_ground_tile.rng:
return
var tree_count = max(0, cell_info.trees.size())
spawn_trees(tree_count)
# Update all rng calls to use parent_ground_tile.rng:
func get_random_position() -> Vector3:
var x = parent_ground_tile.rng.randf_range(-spawn_area_size.x / 2, spawn_area_size.x / 2)
var z = parent_ground_tile.rng.randf_range(-spawn_area_size.y / 2, spawn_area_size.y / 2)
return Vector3(x, 0, z)
func spawn_tree_at_position(pos: Vector3):
var random_index = parent_ground_tile.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 = parent_ground_tile.rng.randf() * TAU
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
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