Minecraft – Detect when player attacks another player

minecraft-commandsminecraft-java-edition

I would like to detect when a player attacks/hits/hurts another player or entity. I have tried to use the AttackTime tag, but it doesn't work. Here is what I have tried (on a 20HZ clock):

First command block:

scoreboard players set @a Attack 0 {AttackTime:0s}

Second command block:

scoreboard players set @a Attack 1 {AttackTime:1s}

Third command block:

tellraw @a[score_Attack_min=1] "Nice shot!"

Best Answer

I figured out how to do this. I use the stat.damageDealt scoreboard objective. First I run the following command once:

/scoreboard objectives add hit stat.damageDealt

Then on the 20Hz clock I do the following:

  • First command block:

    /tellraw @a[score_hit_min=1] "Nice Hit!"

  • Second command block:

    /scoreboard players reset @a[score_hit_min=1] hit

How this works is that points is added to the stat.damageDealt objective each time they hit/attack/hurt an entity or player. Then it runs the command on every player that has hurt another entity or player. When that command is done, the objective gets reset.

How I found this is that on the statistics menu from the pause menu, there is a statistic called Damage Dealt.

EDIT:

In Minecraft 1.9, use the repeating command block instead of a 20Hz clock.