Area2D - Bounding Box Script

Godot Version



Hi, I’m new to Godot but have some years of experience in programming. I’m learning Godot after dropping Unity and I’m impressed how smart this tool is implemented.
I’m implementing a little shooter game with enemies which shall move in groups and want to apply a computed Area2D bounding box arround the enemy group which automatically adjusts when one of the targets is destroyed.
not sure if Godot has this functionality included but due to learning experience I implemented a small script iterating over the Area2D Childs calculating the position and size of the new Area2d rect.
it works as expected but when I add multiple groups to my scene only the last calculated rect is applied to all my nodes. Maybe it has something to do with unique items but haven’t got a clue.

The top group has 1 dummy (ColorRect)
the bottom group 3, but both have the collision area matching 3

Anybody has an idea what I’m missing:

extends Area2D

class_name BoundingBox

const _size: int = 16

func _ready():
	var panel_rect = _get_group_rect()
	$CollisionShape2D.position = panel_rect.position
	$CollisionShape2D.shape.size = panel_rect.size
func _get_group_rect():
	var min_x: float = 10000
	var min_y: float = 10000
	var max_x: float = 0
	var max_y: float = 0
	for child in get_children():
		if child is CollisionShape2D: continue
		min_x = min(min_x, child.position.x)
		min_y = min(min_y, child.position.y)
		max_x = max(max_x, child.position.x)
		max_y = max(max_y, child.position.y)
	var origin = Vector2i(min_x, min_y)
	var end = Vector2i(max_x, max_y)
	var size = end - origin + Vector2i(_size, _size)
	var center = Rect2(origin, size).get_center()
	return Rect2(center, size)

printout for calculated frames:
[P: (8, 8), S: (16, 16)]
[P: (24, 8), S: (48, 16)]

Thanks in advance

I think you just forgot to make a new CollisionShape for each group and you’re telling your code to use the same one for all of them.
Check if that’s the case. You could just make a new one on _ready to make sure it is a fresh one.

Thanks for the quick reply

Screenshot 2023-12-10 at 17.59.34

BoundingBox is an Area2D node with CollitionShape2D, I tried making it unique in the Inspector but didn’t solve the issue

looks like there is a lot to learn :slight_smile:

looks like checking “local to scene” fixed it. Has no description maybe someone knows, at least you reply helped me going through the settings :wink:

Found it

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.