Minecraft – How to target a player that is both in a certain Y coordinate and in a certain radius

minecraft-commandsminecraft-java-edition

I'm working on a parkour map where if you fall off the map, it teleports you back to the start, so I need to teleport 1 player that is both Y=166 (for this example) and in a radius of 50 (for this example). The problem is when I execute the command it teleports all players that are in a 50 block radius, whether there in Y=166 or not, here's the command I'm working off of:
execute @a[y=166,r=59] ~ ~ ~ tp @p -12.5 118 -27.5
and I have it set up in a repeat command block with always active.

Best Answer

Good question. I have spent a few hours playing with the mechanics of target selectors. I have reread the wiki a few times. I came up with a solution but it does not involve radius.

The problem is the initial target selector: @a[y=166,r=59]

This will select any player within a 59 block radius of y=166 directly above or below the command block. (If x and z are not specified it defaults to the command execution position) This radius means above and below y=166. When x and z of player are same coordinates as command block this would select anyone from y=107 to y=225.

If you use a volume argument to specify y, it only selects players inside the specified zone that also happens to be within the radius. Which without x and z seems to be only a few cubes directly above/below command block. Also doesn't work.

Also, I don't recommend using the execute command. Technically your command is finding a player based on the above criteria and then teleporting the nearest player(@p) to that position. Just use the tp command directly while targeting the player you want to with the target selector


One solution would be to specify a zone to target. This would use volume arguments instead of the radius argument. It requires a bit more.

/tp @a[x=X,dx=DX,y=166,dy=0,z=Z,dz=DZ] -12.5 118 -27.5

X and Z specify one corner of the zone tested.

DX and DZ specify the distance from X and Z respectively. (they are a distance, not a coordinate)

Note: Relative coordinates can not be used in the target selector.

Example:

/tp @a[x=-25,dx=50,y=166,dy=0,z=-25,dz=50] -12.5 118 -27.5

This will select and teleport any player between (-25,y,-25) and (25,y,25). This could sort of replace a radius of 50. It is not perfect, it seems to select any player above 164 and below 167.

In your case of a player falling off of a structure it will teleport them once they hit y=166.

Also, the command block has to be located in a loaded chunk. You could use a command block per zone of your map to have small targeted zones or you could put the command block in the spawn chunks and use one large zone that covers your entire map area.

Example of the latter:

/tp @a[x=-5000,dx=10000,y=166,dy=0,z=-5000,dz=10000] -12.5 118 -27.5

This would select and teleport any players between (-5000,y,-5000) and (5000,y,5000) at the correct y level.