Is there anyway to check for a collision within an area immediatly in code and if so how?

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

I want to be able to place blocks in a game but check if any enemies or the player is in the area first before the block is placed. I would be placing the block using the tile map. Area2D does not have any way of checking for collision in code immediately.

:bust_in_silhouette: Reply From: Batti

I’m completly new to Godot but try using Area2D to check collision inside a script.
Attaching the Area2D to the object ( for example a monster ) will create an area ( you don’t say e__e ). Then use the function overlapping_bodies() to check which objects are inside of it. For more information check the documentation inside the engine. Hope it’ll help a bit

:bust_in_silhouette: Reply From: SIsilicon

Have you considered ray casting? Make a RayCast2D child node for your player tree (if you haven’t already). In code you can do this.

#In your player's set block function or something.

#the 20 is half the thickness of the character I presume. You change it.
var ray_dir = (block_pos - get_parent().position).normalized()
$RayCast2D.position = to_local(get_parent().position + ray_dir*20)
$RayCast2D.cast_to = to_local(block_pos)

$RayCast2D.force_raycast_update()

if $RayCast2D.is_colliding():
    #"the grid map" is actually an object reference, not a string.
    if $RayCast2D.get_collider() == "the grid map":
        #proceed to add the block.

I made this up off the top of my head so it may or may not work.

:bust_in_silhouette: Reply From: MysteryGM

Area2D does not have any way of checking for collision in code immediately.

Use the signal for body_entered() and connect the signal with the Area2D node. This way it signals itself that the collision happened.
Because Godot doesn’t have a event system this is the best way to get around it.

:bust_in_silhouette: Reply From: prok

Another way is to use PhysicsDirectSpaceState.IntersectShape().

Here’s a c# sample code:

var polygon = new ConvexPolygonShape2D();  // You should save this variable if it will be used repeatedly.
polygon.Points = new[]
{
    new Vector2(0.0f, 0.0f),
    new Vector2(50.0f, 30.0f),
    new Vector2(50.0f, -30.0f),
};
        
var hits = GetWorld2d().DirectSpaceState.IntersectShape(new Physics2DShapeQueryParameters
{
    ShapeRid = polygon.GetRid(),
    Transform = GlobalTransform,  // This positions the polygon at this node's location.
    Exclude = new Array(this),
});