0 votes

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.

asked May 28 in Engine by MarcPhi (33 points)

1 Answer

0 votes

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

answered May 28 by Panagiotis Halatsako (58 points)

But an area cant detect static bodys to my knowledge

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

In that script, you will have to have a physicsprocess function which will check for the Area2D of each static body with getoverlappingareas() or getoverlappingbodies()

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 physicsprocess 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 _physicsprocess does.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.