Minecraft – How to make players share damage using command blocks

minecraft-commandsminecraft-java-edition

I'm making an adventure map where I want players to share damage – when player 1 takes some amount of damage, player 2 will also get damaged that same amount. I used scoreboards with health, did a scoreboard to test for player's health and I know how to damage using potion effects, but I don't know how to testfor and deal damage to one specific player (the player with higher health).

Could I get some advice on this?

Best Answer

You should use a dummy variable and target selector arguments.

Run once

Have a dummy score, call it healthDif.

/scoreboard objectives add healthDif dummy

Run every tick, in order

Set each players healthDif score to their own health score:

/execute @a ~ ~ ~ scoreboard players operation @a[c=1] healthDif = @a[c=1] health

Subtract the other player's healthDif score from your own:

/execute @a ~ ~ ~ scoreboard players operation @a[c=1] healthDif -= @a[rm=0] health

Now players with a positive healthDif score will have more health than the other player. Target with @a[score_healthDif=1]
Note this will only work for two players. In order for it to work with more, you have to take a few extra steps.


Run once

First you'll need a dummy variable to store miscellaneous variables. Call it vars. Note: If you already have a variable for this (you likely do), you can skip this step.

/scoreboard objectives add vars dummy

Run every tick, in order

Put these between the two commands from before.

First, set the #nplayers to 0:

/scoreboard players set #nplayers vars -1

Now, have each player increment #nplayers:

/execute @a ~ ~ ~ scoreboard players add #nplayers vars 1

Finally, multiply each players healthDif score by this number

/scoreboard players operation @a healthDif *= #nplayers vars

This way, you can have any amount of players, and the system automatically adapts!