Minecraft – way to make a sword strike an enethe with lightning when hit

minecraft-commandsminecraft-java-edition

Is there like a command that can strike a mob or player or both with lightning when hit with a sword? If so super cool, if not 🙁 too bad either way thanks! Unfortunately I have no idea what you guys are talking about I'm not able to speak the language you have answered my question in sorry when your able to speak in English please let me know thanks again 🙂

Best Answer

The "stat.useItem" objective-type can track when a player deals damage with a sword. Unfortunately there are some complications with targeting the struck mob. There isn't really any data to use, apart from guesswork with "HurtTime" tag that will change once the mob is struck, but that doesn't necessarily mean the mob was struck by that player in that instance. The fire damage from lightning itself may cause issues.

As such, the following set of commands (for 1.8.8.) will try to spawn lightning as accurately as possible, but just be aware that it's not possible to be perfectly accurate.

Prerequisites

Objective that automatically increases when a player hits an enemy with a diamond sword.

/scoreboard objectives add UseSword stat.useItem.minecraft.diamond_sword

Objective to track when a mob was struck via "HurtTime".

/scoreboard objectives add MobStruck dummy

Clock Commands

The following must be run in numerical order on a 20-tick-per-second clock.

  1. First, reset the "MobStruck" score for relevant mobs. Using a straight @e will cause the /scoreboard command to be processed equal to the number of all entities, so it's not recommended to do that. This example will affect creepers and zombies only, so you may add more. This sets their score to 0 just before "HurtTime" hits 0, just to reduce command output.

    /scoreboard players set @e[type=Creeper] MobStruck 0 {HurtTime:1s}
    /scoreboard players set @e[type=Zombie] MobStruck 0 {HurtTime:1s}
    
  2. Label mobs who were recently struck. "HurtTime" will be set to 10 when the mob is struck, and then decrease by 1 per tick until it reaches 0 again. This is why a 20t/s clock is required.

    /scoreboard players set @e[type=Creeper] MobStruck 1 {HurtTime:10s}
    /scoreboard players set @e[type=Zombie] MobStruck 1 {HurtTime:10s}
    
  3. Cause players who have used their diamond sword to strike the relevant mobs within a 10-block radius (which you may change).

    /execute @a[score_UseSword_min=1] ~ ~ ~ execute @e[score_MobStruck_min=1,r=10] ~ ~ ~ summon LightningBolt
    
  4. And finally, reset the "UseSword" score for players that have used their sword.

    /scoreboard players set @a[score_UseSword_min=1] UseSword 0