Topic was automatically imported from the old Question2Answer platform.
Asked By
AndrewD
Hi, through which node and how can I track the number of objects in a certain zone? Objects are stored in the form of the variable “export (PackedScene) var”
The following is assuming a 2D-game, but should work similarly for 3D!
Create an Area2D-node and attach a CollisionShape2D to it. It’s shape and size will represent the zone you’re keeping track of. Make sure, each object you want to keep track of has a CollisionShape2D as well. Signals will be emitted when an object enters your zone, depending on the node-type you used for your objects:
area_entered, area_exited
if object is Area2D
body_entered, body_exited
if object is KinematicBody2D or RigidBody2D or StaticBody2D
So connect these signals on the “Zone”-Area2D to functions increasing or decreasing a counter variable to keep track of how many objects are currently inside the zone:
Please note that the entering/exiting body or area is based as a argument to the signal callbacks! This way it’s easy to restrict the counting even further, e.g:
func _on_Zone_body_entered(body):
if body.is_in_group("ShouldCount"):
counter += 1
Check the documentation, if you want to learn more about node groups.