## Recursive function to raycast where the vanilla enderman morph ability should teleport
## Runs initially from `morph/vanilla_activated` then recursively from here
## @s = ldz:raycaster

## Increment the Raycast score on every iteration so we can stop before hitting 300
scoreboard players add @s Raycast 1

## Checks if the path ahead is clear, and then teleports forward if so
tag @s remove ClearPath
execute if score @s Raycast matches ..300 if block ^ ^ ^1 air run tag @s add ClearPath
execute if score @s Raycast matches ..300 if block ^ ^ ^1 end_rod run tag @s add ClearPath
execute if score @s Raycast matches ..300 if block ^ ^ ^1 light_block run tag @s add ClearPath
execute if score @s Raycast matches ..300 if block ^ ^ ^1 ldz:lit_air run tag @s add ClearPath
tp @s[tag=ClearPath,scores={Raycast=..300}] ^ ^ ^1

## If the ClearPath check comes back as false, then backup 1 block and check again to see if it failed because we hit a real block or the edge of simulation distance
## If we hit a real block, then add the `Collision` tag. This way we know whether to bring the player to the ground after teleporting.
execute as @s[tag=!ClearPath] at @s run tp ^ ^ ^-1
execute as @s[tag=!ClearPath] at @s if block ^ ^ ^1 air run tp ^ ^ ^1
execute as @s[tag=!ClearPath] at @s unless block ^ ^ ^1 air run tag @s add Collision

## Recursively call this function as long as the path is still clear and we haven't done more than 300 raycast iterations
execute as @s[tag=ClearPath,scores={Raycast=..300}] run function morph/vanilla_raycast