How to detect when my player hits a specific object in c#

Godot Version

Godot 4.1


I am trying to make a prompt for when my player character when a certain object how do I do this I have a sprite 2D and an Area2D on my block and my player has a collison shape 2D and a sprite 2D in a player charater2D
All help would be appreciated

what body your character use? the body have signals when you attach script to them.

// Using MoveAndCollide.
var collision = MoveAndCollide(Velocity * (float)delta);
if (collision != null)
    GD.Print("I collided with ", ((Node)collision.GetCollider()).Name);

// Using MoveAndSlide.
for (int i = 0; i < GetSlideCollisionCount(); i++)
    var collision = GetSlideCollision(i);
    GD.Print("I collided with ", ((Node)collision.GetCollider()).Name);

My player uses a character body 2D

Did you run code from above?
if you don’t like names you can check if object is class of Player
if(collision.GetCollider() is Player){ … }

Im not sure if this is important but i have a area 2d on the object i want to check collision with and collision shape 2d as a child of it, the code didnt seem to work, but i am also able to walk through the object so that might be a problem on my end

Area2D use signals for Collisions
you can connect your method via editor
in advanced you can pick method to connect

remember your method needed have same arguments to signal (in area is Node2D).
or with Code

public partial class DialogArea : Area2D

        public override void _Ready()
                BodyEntered += MyMethod;

        private void MyMethod(Node body)
                if (body is Player player)

Instead of using an area2D i switched it to static body2D and that has seemed to fix my problems for now

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.