Collision Detection wont happen right away

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

I noticed that if a new node with physics is created, it will only detect collisions after couple of moments. In my current project for example I want to randomly generate forests and therefore I spawn a tree, which then checks wether or not it is overlapping with other trees. But even if it is overlapping it wont detect that, unless I let the node yield for about 0.1 seconds and check afterwards. That is quite a bother since many trees have to be spawned and waiting for each and every one of them takes a couple of minutes. Is there a way to change the need to wait or reduce the required time? Or maybe a workaround without using physics?

how do you check if objects collide? code snippet?

volzhs | 2018-02-07 14:28

I use the get_overlapping_bodies() function of an Area2d, which is a child of the said tree. It returns an empty Array if I don’t let it wait.

My scene tree is a StaticBody2D with a CollisionShape2D, a Sprite and an Area2D with its own collisionshape

This is the code for the tree:

extends StaticBody2D

func _ready():
	pass

func check_kill():
	var timer=Timer.new()
	timer.set_wait_time(0.1)
	timer.set_one_shot(true)
	add_child(timer)
	timer.start()
	yield(timer, "timeout")
	timer.queue_free()
	var area=get_node("Area2D")
	var bodies=area.get_overlapping_bodies()
	if(!bodies.empty()):
		if(!bodies==[self]):
			queue_free()
	area.queue_free()

Freya | 2018-02-07 15:17

(the underscrores from my code got messed up but I hope it should dtill be readable. Couldnt figure out how to paste more than one line into the code sample)

Freya | 2018-02-07 15:19

Area2D has signal for collistion

  • Godot 3.0 - body_entered
  • Godot 2.x - body_enter

you’d better connect this signal to Area2D to check collision.
don’t need to wait specific time.

func _ready():
    area.connect("body_entered", self, "on_body_entered")

func on_body_entered(body):
    # check which body collided

volzhs | 2018-02-07 15:27

It worked, thanks!
How can I mark this question as answered though, since this has been a comment?

Freya | 2018-02-07 16:36

:bust_in_silhouette: Reply From: volzhs

Area2D has signal for collistion

  • Godot 3.0 - body_entered
  • Godot 2.x - body_enter

you’d better connect this signal to Area2D to check collision.
don’t need to wait specific time.

func _ready():
    area.connect("body_entered", self, "on_body_entered")

func on_body_entered(body):
    # check which body collided

copied from comment