Minecraft – Using execute command to teleport a player under a certain height

minecraft-commandsminecraft-java-edition

I am trying to make a parkour map and I want to add checkpoints not by killing them, but by detecting when they go below a certain height. I am currently using this command:

/execute @a[r=68] ~ ~ ~ execute @p[y=27,dx=0,dy=0,dz=0] ~ ~ ~ tp @p 271 43 139

which will search for any players at the height of 27 within a radius of 68 and if a player is found, they will be teleported to 271 43 139.

But I found out one problem with this, if I want to make multiple checkpoints then this command block would only work for a certain range of coordinates and only teleport them to one location no matter where they are.

I thought of a solution where I were to have multiple command blocks at exact locations and with an exact radius, it is going to take a long time. So instead of having a radius relative to the command block, is there a way to find an entity according to specific coordinates?

Best Answer

I would try a completely different way of detecting players below y=27:

/execute @a ~ ~ ~ execute @s[y=0,dx=0,dy=27,dz=0] tp @s @e[tag=teleportTarget,count=1]

This first selects every player, then narrows down that list by only selecting those between y=0 and y=27 (you need no x and z range, but it might be required, so I specified it, too), then teleports them to the nearest entity with the "teleportTarget" tag.

You can restrict that, for example if your map goes into the negative x direction, add ,dx=99999 to only select checkpoints within positive x direction.

Alternatively, you could use your idea of putting command blocks in different places, to be specific, the lowest x, y and z coordinates of the area where you want to teleport people to a certain checkpoint. Then you can simplify that command to:

/tp @a[dx=<range>,dy=27,dz=<range>] <coordinates of checkpoint>