Minecraft – How to teleport a player forward in the direction they’re facing?

minecraft-commandsminecraft-java-edition

I am trying to simulate Mortis from Brawl Stars in Minecraft. In order to do this, I need to teleport the player a few blocks forward every time they click their mouse button to attack. I need help to get a command I can use to teleport a player forward when they attack.

I've already covered how to detect when the player attacks (a damage_dealt scoreboard) but I need to know how to make sure the player moves a few blocks forward no matter which way they're facing.

My current idea is that I use the scoreboard to check that I have attacked with the shovel with nbt:{Mortis:1}. In this way I could use /execute to detect @a[nbt={SelectedItem:{tag:{Mortis:1}}}] and then run a tp.

The problem here is that the destination of tp must be found out by the direction that the player is facing, but I don't know any tag or selector in Minecraft to do that.

Best Answer

This is actually really easy to do using the caret notation for coordinates. Caret notation does relative translation based on the player's left, up, and forward directions (in that order). So, after tagging your player (which you've indicated you're already doing), your command simply becomes

/tp @a[nbt={SelectedItem:{tag:{Mortis:1}}}] ^ ^ ^3

replacing the 3 with an appropriate distance. Do note however, I believe the forward direction is based on the player's view pitch angle, so using this can allow a player to teleport into the air. This can be solved using an execute command specifying the rotation:

/execute as @a[nbt={SelectedItem:{tag:{Mortis:1}}}] at @s rotated ~ 0 run tp @s ^ ^ ^3

(I'm pretty sure that works, haven't been able to test.)