Minecraft checking entity positions

minecraft-java-edition

I have two entities and I want to see if the second entity is x+ or x- to the first entity. I want to do this for all three axis. Anyone know how I can do this? In addition to this, I've tried execute @e[type=Bat,name=Coord1] ~ ~ ~ testfor @e[x=~,y=~,z=~,type=Bat,name=Coord2] to see if the entities are at the same location but it doesn't seem to work.

Best Answer

To test if entities are at the same location, you can use the r argument to test for a radius of 0:

execute @e[type=Bat,name=Coord1] ~ ~ ~ testfor @e[r=0,type=Bat,name=Coord2]

You can use dy, dx and dz to test for an entity inside a cuboid relative to another entity. For example:

execute @e[type=ArmorStand] ~ ~ ~ /say @a[dx=6,dy=5,dz=3]

Would say players in this area (and 5 upwards):

enter image description here

To test for entities in the positive Z direction, you probably want a region that looks something like this:

enter image description here

You can make this bigger, although it will get laggier the larger the area to be checked is.

We need to check both negative and positive X from the entity (it is not at one of the corners of the region). To do this, we could use two separate testfor commands. One for +Z +X, and one for +Z -Z.

We can also use the coordinates in the execute command to have a different starting point, like this:

execute @e[type=ArmorStand] ~-7 ~ ~ /say @a[dx=14,dy=5,dz=10]

So we go -7 in the x direction, and then search a 17 by 5 by 10 region starting from there:

enter image description here

Applying this to your bat situation:

execute @e[type=Bat,name=Coord1] ~-7 ~-7 ~ testfor @e[dx=14,dy=14,dz=10,type=Bat,name=Coord2]

Should detect bats in the positive x direction. You'll need to create a command for each negative and positive in each axis. For example, for positive z:

execute @e[type=Bat,name=Coord1] ~ ~-7 ~-7 testfor @e[dx=10,dy=14,dz=14,type=Bat,name=Coord2]