- Edited
I know there's probably dozens of posts where this is talked about, but I just need someone to look over my code, and tell me if I am missing something, because I've been at this for hours. I working on a dungeon generator. The code for the room spawning works fine, the problem is where I check if they're colliding with each other. Sometimes, it spawns a rooms without any colliding with each other, others they're all in a bunch together.
I am using AABB to check for the collisions, and inside the if statement if box1.intersects(box2), at the end i included to move rooms again, in case that they collided with other different ones, at the time of moving them. Any help is appreciated!
@export var scenes : Array[PackedScene] = []
@export var scenes_instances : Array[int]
@export var number_of_units: int
@onready var rng = RandomNumberGenerator.new()
var unit = Vector3(5,0,5)
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
spawn_rooms()
move_rooms()
func spawn_rooms():
for i in len(scenes):
for j in range(scenes_instances[i]):
var scene = scenes[i].instantiate()
add_child(scene, true)
## rotate and position each scene randomly
## first we generate a random rotation
var rand_rotation = rng.randi_range(1,4) * 90
## then we translate the radians into degrees
scene.rotation.y = deg_to_rad(rand_rotation)
## randomly change the position
scene.position = Vector3(rng.randi_range(0,number_of_units) * 5, 0, rng.randi_range(0,number_of_units) * 5)
func move_rooms():
for i in range(get_child_count()):
for j in range(i+1, get_child_count()):
## get size and position of both rooms to compare
var name = get_child(i).get_name()
var box1_position = get_child(i).position
var box1_size = get_child(i).get_child(0).size
var box2_position = get_child(j).position
var box2_size = get_child(j).get_child(0).size
var box1 = AABB(box1_position, box1_size)
var box2 = AABB(box2_position, box2_size)
if box1.intersects(box2):
var inter_size = box1.intersection(box2)
print(name)
#await get_tree().create_timer(1.0).timeout
if get_child(i).position.x > get_child(j).position.x:
get_child(i).position.x += inter_size.size.x
get_child(j).position.x -= inter_size.size.x
else:
get_child(i).position.x -= inter_size.size.x
get_child(j).position.x += inter_size.size.x
#await get_tree().create_timer(1.0).timeout
if get_child(i).position.z > get_child(j).position.z:
get_child(i).position.z += inter_size.size.z
get_child(j).position.z -= inter_size.size.z
else:
get_child(i).position.z -= inter_size.size.z
get_child(j).position.z += inter_size.size.z
move_rooms()
picture is after the code finished running and the scene renders