Collision detection of Area2D doesn't work in runtime

Godot Version

4.2.1

Question

What’s the problem?

I’m tring to use Area2D and a temp Area2D for access range detection.
But it doesn’t works.
it should be detected the temp Area2D but it doesn’t.
I’m sure that their collision shape are right.

My scene tree:


My code:

Entity:

class_name Entity
extends Node

@export var access_range: Area2D;

func check_access_range(target_world: World, target_position: Vector2) -> bool:
    if not access_range:
        return true
    var body = target_world.create_temp_physics_body(target_position)
    body.force_update_transform()
    await get_tree().physics_frame
    await get_tree().physics_frame
    var bodies = access_range.get_overlapping_bodies()
    var result = bodies.has(body)
    body.queue_free()
    return result

World:

class_name World
extends Node2D

signal layer_changed(layer: int, from: int);

var layer: int = 0:
    set = set_layer;

var collision_layer: int:
    get: return 1 << layer

static var temp_physics_body_shape = preload("res://types/world/temp_physics_body_collision_shape.tres")

func set_layer(value: int) -> void:
    var old = layer;
    layer = value;
    layer_changed.emit(value, old);

func create_temp_physics_body(position: Vector2) -> Area2D:
    var collision_shape = CollisionShape2D.new()
    collision_shape.shape = temp_physics_body_shape
    var body = Area2D.new();
    body.add_child(collision_shape)
    body.collision_layer = collision_layer
    body.position = position
    %TempNodes.add_child(body);
    return body

It’s hard to help in this case. Your code looks mostly okay. It looks like there are bodies in the bodies array (in the breakpoint).

Have you made any progress?

you use unique name for TempNodes, but here you dont have it assigned with access with unique name
image

1 Like

No, I gave up in this way. But I still want to know what’s happend and how to fix it.

In the breakpoint, the Area2D doesn’t detected another Area2D node(variable body).

It’s instantiated by a scene in runtime.

World
 |- Floors - TileMap
 |- Entities - Node2D
 |- TempNodes - Node2D

And i think this line is work well. It added the body correctly.

i see, so you just need to save the current TempNodes’ node by saving the reference into a variable (right after you instantiated it), then use the temp_nodes variable to be the parent to add child.
Using % without making it as access with unique name, won’t be able to access it like that.

1 Like