How to detect a player at Y level 2 anywhere in the world?

I've made a practice run for parkour in my world and when I fall, I have to /kill or fly back up and it is annoying and takes time, so I was wondering if I could use commands to teleport me to a certain position if my Y level is 2 or less. I am in 1.16.3.

I tried to use the /execute commands but I don't think I am using it right, this is the command i am trying to use:

/execute if entity @p[y=2] run teleport @p 162 10 -652.

Anytime I've used this it just teleports me infinitely to the position, even if I am not at Y level 2. What is going on, and how do I fix it?


Simple solution

Let's look at the Minecraft Wiki page on target selector arguments.

Position arguments

[x=<value>,y=<value>,z=<value>] Define a position in the world the selector starts at, for use with the distance argument or the volume arguments, dx, dy and dz. Defining the position alone can be used with a target selector that selects the nearest entity from those coordinates, but it otherwise has no use, so applying it (and only it) to @e still selects all entities in the same dimension.

Therefore, you cannot use the position arguments x, y, and z on their own, and it is impossible to select targets on a certain Y level anywhere in the world. You need to give additional information to the target selector.

The most basic way is by using the distance argument. This will detect targets within certain distances of the specified position. Here are some examples:

  • @p[x=11,y=22,z=33,distance=5]: Select targets exactly 5 blocks from coordinates (11, 22, 33).
  • @p[x=11,y=22,z=33,distance=3..6]: Select targets between 3 and 6 blocks from coordinates (11, 22, 33).

You can either use that, or use the volume arguments, dx, dy, and dz. They're a bit to complicated to explain, and the Minecraft Wiki explains them far better than I can ever answer here. Visit the link above for more information.