Minecraft – How to trigger Command Blocks when a player walks in a certain area

minecraft-commandsminecraft-java-edition

I'm currently making an adventure map and I want to know how to trigger Command Blocks when a player walks through a certain area. For example, if a player walks through a certain part of a cave, it would say "Don't go down there", or something. Or it could trigger a jump scare (but that's not what I'm looking for).

Specifically, I'm making it so that when the player walks through an area, it says "I think it would be a good idea to go exploring." in a first person perspective.

Best Answer

To test for a player in some distance from a certain place, use:

/testfor @a[x=X,y=Y,z=Z,r=R,rm=RM]

Where X, Y and Z are the middle coordinates of the area to test for a player, R and RM specify the minimum and maximum distances from the specified coordinates, respectively.

To run a command, eg. /say Hello when the testfor command returns true, place the @a[] part into an /execute command:

/execute @a[x=X,y=Y,z=Z,r=R,rm=RM] ~ ~ ~ /say Hello