detect static body collision

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MarcPhi

Hello is there a way to detect if an static body overlaps with other static bodies?
I want to check if a space is already occupied before i spawn the static body.

:bust_in_silhouette: Reply From: Panagiotis Halatsako

Add an Area2d as a child which will work on a separate 2d layer to detect the collisions

But an area cant detect static bodys to my knowledge

MarcPhi | 2020-05-28 22:49

I assume you have a node with a script that spawns the static bodies.

In that script, you will have to have a _physics_process function which will check for the Area2D of each static body with get_overlapping_areas() or get_overlapping_bodies()

If the value is not empty then it overlaps with an area and you will have to move or remove it programmatically

I made a TemplateStaticBody as follows:

StaticBody2D (TemplateStaticBody)
| -> Sprite
     | -> Area2D
          | -> CollisionShape2D (For area2d detection)
| -> CollisionShape2D (For static body)

Then I made two inherited scenes one BlackPawn and one WhitePawn.
Created a Node2D scene (World) and added them inside overlapping each other. Then made a script to that World, and did the following:

func _ready():
	print($WhitePawn/Sprite/Area2D.get_overlapping_areas())
	print($BlackPawn/Sprite/Area2D.get_overlapping_areas())

This did not show any overlapping areas.
Then, did a _physics_process call:

func _physics_process(delta):
	print("Tick!")
	print($WhitePawn/Sprite/Area2D.get_overlapping_areas())
	print($BlackPawn/Sprite/Area2D.get_overlapping_areas())	

Output was:

Tick!
[]
[]
Tick!
[[Area2D:1201]]
[[Area2D:1196]]
Tick!
[[Area2D:1201]]
[[Area2D:1196]]
....

Which proves that there are overlapping bodies. I tried to yield one idle frame in _ready() but it didn’t produce the overlapping either, so it needs a minimum threshold of time to detect the overlapping areas that _physics_process does.

Panagiotis Halatsako | 2020-05-29 04:18