Detect when player attacks another player

Detect when player attacks another player - A Man in Green Crew Neck T-shirt Playing Computer Games

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

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.




Pictures about "Detect when player attacks another player"

Detect when player attacks another player - A Man in Black Crew Neck T-shirt Using a Computer Keyboard
Detect when player attacks another player - Woman in Brown Shirt Using Computer
Detect when player attacks another player - Man kicking ball during football match in park



How do you detect if a player hits an entity?

Test if Nearest Player is at Level 20 experienceType the command in the chat window and press the Enter key to run the command. Once the cheat has been entered, the testfor command will test the experience level of the nearest player.



Enemy Aggro - Attack player when too close




Sources: Stack Exchange - This article follows the attribution requirements of Stack Exchange and is licensed under CC BY-SA 3.0.

Images: Yan Krukov, Yan Krukov, Yan Krukov, Chuck Johnson