Minecraft – Change a scoreboard objective is a player gets within proximity of an entity

minecraft-commandsminecraft-java-edition

I've been playing with command blocks lately, and I'm playing around with one of those "server mods in vanilla" type mechanisms. Basically, I've got a clock set up that makes players turn invisible when they're sneaking (I'm building this in 1.9, using the new repeating/chained blocks). That sequence looks like this:

Run this to initialize:

/scoreboard objectives add sneaking stat.sneakOneCm

Run these in sequence every tick:

/effect @a[score_sneaking_min=1] minecraft:invisibility 1 0 true
/scoreboard players reset @a[score_sneaking_min=1] sneaking

The thing is, I want to make it so that if a player gets too close to another player or hostile mob, they become exposed, preventing them from getting the invisibility effect. I got as far as modifying the above command to check a scoreboard objective:

/effect @a[score_sneaking_min=1,score_tooClose=0] minecraft:invisibility 1 0 true

But I don't really know how I would test for that. I thought maybe something like /execute @a ~ ~ ~ testfor (etc.) but then I wouldn't be able to do anything with the result of the test, because it's being executed on behalf of something that doesn't care. I'm just not sure what the right train of thought here is.

Thanks for any help you can provide.

Best Answer

You should run the following command before the /effect command, to make all entities with the tag "Detector" give all players within a radius of 10 a tooClose score of 1:

/execute @e[tag=Detector] ~ ~ ~ /scoreboard players set @a[r=10,rm=1] tooClose 1

And then reset the score after the /effect command has been run:

/scoreboard players set @a[score_tooClose_min=1] tooClose 0

You can replace r=10 with your detection radius, and tag=Detector with however you're identifying the mobs you are wanting to detect the player, or keep the tag and do something like to add the tag to mobs:

/scoreboard players tag @e[type=Zombie] add Detector