Zombie still dealing damage despite not being in range

Hello, I am making zombies for a game, but the problem I come across is that when the zombie attacks, it has a specific attack range, in begins an attack animation when a player is within range. Once a specific animation event is reached it’ll damage the player if they are still in range, but it still damages the player, despite the code looking correct:

local function attack(target)
	local distance = (entity.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
	
	if distance <= attackRange and canAttack then
		canAttack = false
		attackAnim:Play()
		entity.Humanoid.WalkSpeed = 0
		
		local attackSound = generateSound(entity.HumanoidRootPart.AttackSounds)
		task.wait(0.5)
		attackSound:Play()
		DebrisService:AddItem(attackSound, attackSound.TimeLength)
		
		attackAnim:GetMarkerReachedSignal("Attack"):Wait()
		if distance <= attackRange then -- I would expect this to work, but it doesn't.
			target.Humanoid.Health -= damage
		end
		
		attackAnim.Ended:Wait()
		entity.Humanoid.WalkSpeed = 14
		task.wait(attackDelay)
		canAttack = true
	end
end

I’d just like someone to tell me how I would go about fixing this.

Based on the code you provided, it looks like the attack animation is triggering correctly, but the damage is still being applied even if the player has moved out of range. One thing you can try is adding a check for the player’s position after the attack animation is complete, to ensure they are still within range before applying damage. Here’s an updated version of the code that includes this check:

local function attack(target)
    local distance = (entity.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude

    if distance <= attackRange and canAttack then
        canAttack = false
        attackAnim:Play()
        entity.Humanoid.WalkSpeed = 0

        local attackSound = generateSound(entity.HumanoidRootPart.AttackSounds)
        task.wait(0.5)
        attackSound:Play()
        DebrisService:AddItem(attackSound, attackSound.TimeLength)

        attackAnim:GetMarkerReachedSignal("Attack"):Wait()
        if distance <= attackRange and (entity.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude <= attackRange then
            target.Humanoid.Health -= damage
        end

        attackAnim.Ended:Wait()
        entity.Humanoid.WalkSpeed = 14
        task.wait(attackDelay)
        canAttack = true
    end
end

This checks the distance between the zombie and the target player after the attack animation is complete, and only applies damage if the player is still within range. I hope this helps!

That worked! I can see the mistake I made, the distance is only compared at the beginning.
Now I just have to add that one line of code into the scripts of all the zombies that I created. :slight_smile: