Minecraft Command setblock relative to where player is looking

Is it possible to place a block in front of the player or entity? For example, if I'm facing north, put the block towards the north. East, put the block towards the east, etc.

Thanks in advance.

If this is a duplicate, feel free to say that. I will not be offended.


Solution 1:

Use the ry and rym selectors. When a player is facing north the player selector will be @p[rym=135,ry=180], when a player is facing west the player selector will be @p[rym=90,ry=135], when a player is facing south the player selector will be @p[rym=45,ry=90] and when a player is facing east the player selector will be @p[rym=0,ry=45]. To set the block, use the following commands:

/execute @p[rym=135,ry=180] ~ ~ ~ /setblock ~ ~ ~-1 (BLOCK FOR NORTH)
/execute @p[rym=90,ry=135] ~ ~ ~ /setblock ~-1 ~ ~ (BLOCK FOR WEST)
/execute @p[rym=45,ry=90] ~ ~ ~ /setblock ~ ~ ~1 (BLOCK FOR SOUTH)
/execute @p[rym=0,ry=45] ~ ~ ~ /setblock ~1 ~ ~ (BLOCK FOR EAST)

Solution 2:

You can use the caret notation to select positions in front of the player:

/setblock ^X ^Y ^Z minecraft:your_block

where:
X = offset left of player's feet
Y = offset above player's feet
Z = offset in front of player's feet