Detect when player attacks another player
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.
This answer is based on @CommandFox's answer and my own (totally awful) idea for a solution. However, I found that combination of the two adds a possible limitation to hurting specific entities.
First, create two scoreboard objectives: didDamage
and hurtTime
scoreboard objectives add didDamage stat.damageDealt
scoreboard objectives add hurtTime dummy
Then, create a fill clock and run the following commands:
scoreboard players add @e hurtTime 1
scoreboard players set @e hurtTime 0 {HurtTime:0s}
execute @e[score_hurtTime_min=1,score_hurtTime=1] ~ ~ ~ tellraw @a[score_didDamage=1] "Nice hit!"
scoreboard player set @a didDamage 0
So far, we have gained nothing by using the hurtTime
objective. The main benefit of it is that it can be limited using its target selector. For example, using
scoreboard players add @e[type=Zombie] hurtTime 1
scoreboard players set @e[type=Zombie] hurtTime 0 {HurtTime:0s}
makes it so that the message only appears when you actually hit a zombie. Using multiples of this command block pair makes it possible to select multiple entities.