
Minecraft JE: 1.13+ 实现检测实体视线
在地图 illusion 的开发中,需要实现功能:检测目标是否在玩家的视线范围内
原本的实现思路
原本的实现思路是判断玩家前方 r 格 r 半径 内是否有目标实体,如果有则执行指令

即 execute as player at @s positioned ^ ^ ^r run execute as @e[distance=..r] run <command>
但是这种方法有一个问题:视线是一个圆锥体,而不是一个球体,这样判断的范围过于模糊
进阶的实现思路
从玩家前方 r 格 左侧 rx 格 右侧 rx 格 展开球体,判断玩家是否在交界处

但这种方法过于复杂,且实现效果一般
使用 execute 实现检测实体视线
后来在 StackExchange 的帖子上看到了一个更好的方法:
execute
as @a # For each player,
at @s # start at their feet.
anchored eyes # Looking through their eyes,
facing <X Y Z> # face perfectly at the target
anchored feet # (go back to the feet)
positioned ^ ^ ^1 # and move one block forward.
rotated as @s # Face the direction the player
is actually facing,
positioned ^ ^ ^-1 # and move one block back.
if entity @s[distance=..0.6] # Check if we're close to the
player's feet.
run
say I'm facing the target!
-
通过
execute as, at定位到玩家位置 -
通过
anchored eyes定位到玩家的眼睛位置 -
通过
facing更改指令的视线方向 -
通过
anchored feet定位到玩家脚部位置 -
通过
positioned移动到玩家前方一格 -
通过
rotated as旋转到玩家的实际视线方向 -
通过
positioned移动到玩家后方一格 -
通过
if entity判断视线是否重叠(即看向目标的角度和玩家的角度是否一致) -
如果重叠,则执行指令


评论
评论加载中…