I am trying to teleport a mob directly behind the selected player. I have tried using relative location of the player's head (^ ^ ^) but that caused the entity to suffocate underground when you look up. is there any way to tp it that way without counting looking up and down (y direction)? or is there another way to solve this problem?
@s be the player, and
@e[tag=tp,limit=1] be the entity to teleport. Here is an example with one command:
execute at @s rotated ~ 0.0 run tp @e[tag=tp,limit=1] ^ ^ ^-2
at @s: Moves the current position to the position of
@s, changes the current rotation to the rotation of
@s, and ensures the current dimension is the same dimension of
rotated ~ 0.0: Keeps the Y-rotation (horizontal) the same, but changes the X-rotation (vertical) to 0.0, meaning that any vertical rotation is ignored.
tp @e[tag=tp,limit=1] ^ ^ ^-2: Teleports the entity to the block two blocks behind
@s. We cancelled out the vertical rotation with step 2, so only the horizontal rotation is taken into account.
The solution revolves around teleporting it using
^ ^ ^ ~ 0, where the last two are the x y rotations (give the zombie the same x rotation as the player, but the y make it 0), then immediately teleport it using
^ ^ ^-z, where z is the amount of blocks you want the mob to be behind you. Working example:
tag @e[type=minecraft:zombie,limit=1,sort=random] add tp # Tag random zombie execute as @e[tag=tp] at @r run tp @s ^ ^ ^ ~ 0 # Teleport to random player execute as @e[tag=tp] at @s run tp @s ^ ^ ^-2 # Move it back 2 blocks tag @e[tag=tp] remove tp # Untag zombie