How do i kill mobs in a radius of 2 blocks from my armorstand using a commandblock 1.16.2

I am making a map where the an armor stand represents the player, so the armorstand keeps getting teleported to the player. I also want to make enemies and if an enemy (zombie) gets in a radius of 2 blocks of the armorstand it dies.

I already had an command, but that killed all zombies 2 blocks from the command block, not the armor stand.

Can anyone help me?


Solution 1:

The armor stand can only teleport to the player when there is only one player. If not, then the armor stand cannot be automatically moved, because there are multiple possible targets that the armor stand can teleport to. However, to kill all the mobs within 2 blocks is simple.

Have a repeating command block, set to always active, with command:

/execute at @e[type=armor_stand] run kill @e[type=!armorstand,type=!player, distance=0..2]

The @e[type=armorstand] executes this only on armor stands, and not on other entities like pigs or players. The [type=!armorstand,type=!player, distance=0..2] part kills all entities that are not players or armor stands that are less than 2 blocks from the armor stand. This prevents the armor stand from disappearing or the player being killed due to being inside the "force field."

I hope this helps.