###Godot Version 4.1
##I’m making a game, and I’m trying to figure out what I need to do to detect if an object is in the same area as my player character. I assume I need to add some node to the object, and some node to player, and then add a code in my player script that the object has left the area, but I don’t know what nodes exactly to use.
There’s a handy node called “Area2D” (or Area3D). You first need an Area2D to define the area that you’re looking for. Add a CollisionShape2D or CollisionPolygon2D as a child of it and give it a shape until it looks right. Do the same thing on the player and the object.
To detect if the object is in the same area as the player, you can call
area.get_overlapping_areas() on the big area. Or you could use the
area_entered signal and keep track of which areas enter and which areas exit with
Ok, so I’ve added the collision shapes, but I’m having a tough time figuring out how to add the code that this box is colliding with that box. Do I need a script for both the object and the player? And do I need to connect the signals between the nodes, if so, how do I do that and still have them be separate scenes, and have multiple clones of the objects all sending signals?
The number of scripts depends on what you want to happen. If you want the player to do something, add a script to the player. If you want the object to do something, add a script to the object. And add a script to the big area if you want that to do something to. You can connect signals via code if they’re not in the same tscn file.
Ok, so how do I connect a signal that the player’s area has entered the area of the object?
Through the editor? Click on the signals tab and then select the correct signal (“area_entered”) and the correct function.
Through code, type
I tried adding the code but this happened:
Is that inside a function?
No. When I put it in a function do I need to add a colon and have that line be what I want to happen when the hit boxes collide?
Now that I’ve added it to a function, it says receiving_function isn’t declared in the current scope.
Right, you need to make the function yourself so that it does what you want it to do.
It says it doesn’t know what player_area means now
That should be a reference to the player’s area node. I don’t know what you called it so I can’t give you the reference.
I highly recommend this tutorial that goes over all the basics of the 2D engine. It really gave me a great base/jump-start (every question you ask here for example is answered there via practice, which is best way to learn ofc): https://www.youtube.com/watch?v=nAh_Kx5Zh5Q&t=1s