• Godot Help
  • How to only attack first zombie if multiple are in the same spot?

I'm currently trying to develop a Plants Vs Zombies fangame in Godot 4.4. But whenever 2 or more zombies are eating a plant and get hit, they all take damage when I only want the zombie who attacked first to get hit. I've tried searching up solutions but I couldn't figure anything out. Does anyone know how to stop this from happening?

  • Maybe this helps.

    extends Area2D
    
    func _ready():
    	connect("on_body_entered", self, "projectile_on_body_entered")
    
    var has_damaged = false
    func projectile_on_body_entered(other):
    	# If true, then the projectile has already hit something and we can ignore
    	# this collision
    	if (has_damaged == true):
    		return
    	
    	# Check if the body collided with is something we can damage.
    	if (other.has_method("hurt")):
    		# Damage the body and do anything else needed here (like sound effects)
    		other.hurt()
    		# Set has_damaged to true, so we know to ignore damaging
    		# anything else
    		has_damaged = true
    		# free it using queue_free
    		queue_free

    https://godotforums.org/d/24023-arrow-collide-with-multiple-enemies

If the Zombies are inherited from a common scene, are you changing the damage property of a single Zombie's instance, or a property that they share?

    Maybe this helps.

    extends Area2D
    
    func _ready():
    	connect("on_body_entered", self, "projectile_on_body_entered")
    
    var has_damaged = false
    func projectile_on_body_entered(other):
    	# If true, then the projectile has already hit something and we can ignore
    	# this collision
    	if (has_damaged == true):
    		return
    	
    	# Check if the body collided with is something we can damage.
    	if (other.has_method("hurt")):
    		# Damage the body and do anything else needed here (like sound effects)
    		other.hurt()
    		# Set has_damaged to true, so we know to ignore damaging
    		# anything else
    		has_damaged = true
    		# free it using queue_free
    		queue_free

    https://godotforums.org/d/24023-arrow-collide-with-multiple-enemies