视线检测
简介
作者: @AjaxGb
该指令技术可检测目标是否正在注视玩家/实体/坐标,并执行您指定的指令。
指令
BP/functions/wiki/detect_state/player/is_looking_at.mcfunction
yaml
execute as <目标> at @s anchored eyes facing <实体 | 坐标> positioned ^^^1 positioned ~~-1.62~ rotated as @s positioned ^^^-1 if entity @s[r=0.2] run <指令>
可视化演示:

注:此为粗略示意图,非精确测量数据。
指令解析:
as <目标>- 设置执行目标。例如:
as @p(最近的玩家)as @e[type=zombie](所有僵尸)
- 设置执行目标。例如:
at @s- 将执行位置设定在目标脚部位置
anchored eyes- 将执行位置上移至目标眼部高度
facing <实体 | 坐标>- 设置执行朝向面对实体或坐标。例如:
facing 0 0 0朝向坐标0,0,0facing entity @e[type=pig,c=1] eyes(朝向最近的猪的眼睛)facing entity @e[type=cow,r=30] feet(朝向30格范围内牛的脚部)facing entity @e[type=zombie] feet(朝向僵尸的脚部)
- 设置执行朝向面对实体或坐标。例如:
positioned ^^^1- 从当前位置沿实体/坐标方向前移1格
positioned ~~-1.62~- 将执行位置沿Y轴降至脚部高度(即眼部下方1.62格)
- 注意:由于MCPE-165051漏洞,此处不能使用
anchored feet替代
rotated as @s- 将执行朝向恢复为目标原始朝向
positioned ^^^-1- 从当前位置沿目标面朝方向后退1格
if entity @s[r=0.2]- 检测目标是否位于执行位置0.2格半径范围内(即判断经过前后移动后是否大致回到目标脚部位置)
- 调整"有效范围"阈值可修改
0.2参数:- 建议取值在
0.2至2之间(取值为2时即使反方向注视也会被判定为有效) - 实际应用中建议保持小于
1的值
- 建议取值在
- 具体视角计算方式见下文
应用示例:
- 当玩家注视带有'target'标签的牛或羊时执行
/say指令:
BP/functions/wiki/detect_state/player/is_looking_at/target.mcfunction
yaml
execute as @a at @s anchored eyes facing entity @e[type=cow,tag=wiki:target] eyes positioned ~~-1.62~ positioned ^^^1 rotated as @s positioned ^^^-1 if entity @s[r=0.2] run say hello cow!
execute as @a at @s anchored eyes facing entity @e[type=sheep,tag=wiki:target] eyes positioned ~~-1.62~ positioned ^^^1 rotated as @s positioned ^^^-1 if entity @s[r=0.2] run say hello sheep!
- 当玩家注视坐标
(10, 20, 30)或(6, 7, 8)时执行/say指令:
BP/functions/wiki/detect_state/player/is_looking_at/position.mcfunction
yaml
execute as @a at @s anchored eyes facing 10 20 30 positioned ~~-1.62~ positioned ^^^1 rotated as @s positioned ^^^-1 if entity @s[r=0.2] run say hello block!
execute as @a at @s anchored eyes facing 6 7 8 positioned ~~-1.62~ positioned ^^^1 rotated as @s positioned ^^^-1 if entity @s[r=0.2] run say hello block!
替代结构:
BP/functions/wiki/detect_state/player/is_looking_at.mcfunction
yaml
execute as <目标> at <坐标 | 实体> facing entity @s eyes positioned as @s positioned ^^^1 rotated as @s positioned ^^^1 if entity @s[r=0.02] run <指令>
若不需要检测目标是否注视实体眼部,而只需检测脚部或坐标时,可采用此结构,省去anchored eyes指令,因为执行起始位置已是实体/坐标而非目标。
视角计算
如需根据视角角度计算触发半径(r),可使用以下公式(其中α为期望的触发角度范围):
r = 2 * sin ( α / 2 )逆向计算特定半径(r)对应的视角角度:
α = sin^(-1) (r / 2) * 2注意:根据计算器类型可能需要将弧度转换为角度
按此计算,示例值r=0.2对应的有效视角范围约为12°(即左右各允许偏差6°仍会被判定为有效注视)。



