I have been trying to add an attack to my character, but the Area2D node is working unexpectedly.
when the player left clicks it instantiates an Area2D with some code checking for overlapping bodies with the get_overlapping_bodies function I also tried something similar with signals, but for some reason the area doesn’t detect collisions right away (it seems to take 2-3 frames) why does this happen and how do I fix it?
Maybe one frame delay is expected when using get_overlapping_bodies(), not sure where the other delay is coming from though
get_overlapping_bodies() const
For performance reasons (collisions are all processed at the same time) this list is modified once during the physics step, not immediately after objects are moved. Consider using signals instead.
Area2D nodes need time to properly initialize in the physics system when dynamically created. When you instantiate an Area2D, it takes 1-2 physics frames before its collision detection fully activates.
My usual work around is just using Raycasting. My child.
func attack():
var raycast = RayCast2D.new()
add_child(raycast)
raycast.target_position = Vector2(attack_range, 0)
raycast.force_raycast_update() # This forces immediate collision check
if raycast.is_colliding():
var body = raycast.get_collider()
if body.has_method("take_damage"):
body.take_damage(damage)
raycast.queue_free()
(This is all in code but you might want to add it as a prepacked scene the instantiate that scene with the raycasts already attached.)