How do I target players with only a certain X, Y, or Z coordinate?

I am trying to test for any player that is on Y level 118.

Here is the command I am using:

/testfor @a[y=118]

The problem is, the command isn't working as expected. In my chat when I type this command, it reads:

Found Boomcrasc078 

The problem is, I am not on y=118 when I run this command. What could be the problem?

I have also tested with a space:

/testfor @a [y=118]

but it still doesn't work.


Solution 1:

You can't use target selectors with x, y, and z alone. You need to provide some additional information to the target selector.

Here are some additional things you can provide.

  • r and rm: Selects entities by distance. For example:

    /testfor @a[x=0,y=0,z=0,r=10,rm=5]
    

    means that entities not more than 5 blocks away from (0,0,0) but not less than 3 blocks away will be selected.

  • dx, dy, and dz: Selects targets in a rectangular volume.
    This one is more complicated, and it's too much to explain clearly in this answer. But you can find more about it in the Minecraft Wiki: Commands

The Minecraft Wiki also states about the x, y, and z 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 world.

This means that it won't be easy to select everyone on a certain Y level. You should instead use a different approach, by testing for everyone nearby a certain point in your world using the distance arguments, r and rm. If you still want to select everyone on Y level 118, you should consider learning how dx, dy, and dz work using the links above.