How do I give players slowness if they have low health? [duplicate]

I'm making a minigame in which I'm adding a slowness factor when your health gets low.

I'm trying to give Slowness I to anyone with less than 7 hearts and Slowness II to people with less than 4 hearts. The effect would disappear if your health was regenerated.

Actually, I don't know where to even start. I made an objective scoreboard with health of every player using /scoreboard objectives add HealthBar health HealthBar, so what next?


Solution 1:

To accomplish this, you need to use the /effect command and an @a selector that selects all the players with your given criteria.

Having a scoreboard already set up is a good start. You can select all players with a maximum score in objective name with @a[score_name=x]. So, in this case, you would use @a[score_HealthBar=14] (since health is tracked in half-heart increments).

The effect command syntax is /effect give <player> <effect> [seconds] [amplifier] [hideParticles]. <player> will become your target selector from above. <effect> is a status effect ID (in this case, minecraft:slowness). [seconds] doesn't matter too much if you're constantly reapplying this, so I would just set it to 10, just to make sure the effect doesn't clear before the command runs again. [amplifier] is a little weird; it corresponds to how strong the effect should be, above 1. This means that to get level 2, you'd enter a 1 here.

You can also clear effects with /effect clear <player> [effect], and invert your selector with score_name_min, to achieve the opposite effect for players with at least 7.5 hearts.

All of these elements come together to give you the following commands:

/effect give @a[score_HealthBar=14] minecraft:slowness 10 1
/effect clear @a[score_HealthBar_min=15] minecraft:slowness

Plug these into a pair of repeating command blocks, and you should be good to go.