How do I testfor a player hitting a mob?

How do I testfor a player hitting a mob? - A Man Playing Gold on the Field

I'm making a custom survival map, and one thing i'd like to implement is custom mobs, but I would also like to get a sound played everytime I hit it myself, either with bow, or sword, or even fists, as long as I can play a sound when a player hurts the custom mob only.

I'm pretty sure i'd have to use an /execute command for thid, but I just don't know really how to use multiple commands with one single command block, and also is it possible to set a score for the mob, and use that for the /execute command?

The mob's name is "Ghost", and it's a Ghast.



Best Answer

You cannot test for a specific player hurting a mob.

However, you can test for a mob being damaged:

/scoreboard players tag @e[name=Ghost,tag=!Hurt] add Hurt {HurtTime:10s}
/scoreboard players tag @e[name=Ghost,tag=Hurt] remove Hurt {HurtTime:9s}

From here, you now know that a Mob is hurt, and can do things reliably, like play a sound:

/execute @e[name=Ghost,tag=Hurt] ~ ~ ~ /playsound sound @a ~ ~ ~ 1 1 

Now, this assumes that the mob won't get hurt unless there's a player near it, which isn't an unfair observation. It will also play the sound to all players on the server, centered on the location of the Mob.




Pictures about "How do I testfor a player hitting a mob?"

How do I testfor a player hitting a mob? - Man in White T-Shirt and Black and White Pants Playing Golf
How do I testfor a player hitting a mob? - A Man Holding a Golf Club
How do I testfor a player hitting a mob? - A Man Playing Gold on the Field



How do you detect if a player hits an entity?

How to Enter the Command
  • Test if Players are within 10 blocks. In this example, we will test to see if there are any players within a 10 block radius with the following command: /testfor @a[r=10] ...
  • Test if Mooshrooms are within 50 blocks. ...
  • Test if Nearest Player is at Level 20 experience.




  • Damage Detection in Minecraft Bedrock! (Windows 10, PS4, Xbox, Pocket Edition)




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

    Images: cottonbro, cottonbro, cottonbro, cottonbro