Lua光线投射异常

我有这个新的高效光线投射代码:

vectorX, vectorY = math.cos(r * math.pi/180), math.sin(r * math.pi/180)

wallDistanceX, wallDistanceY = v[3] - v[1], v[4] - v[2]
wallParallelX, wallParallelY = -wallDistanceY, wallDistanceX
rayX, rayY = v[1] - cam.x, v[2] - cam.y

Distance = (
    (rayX * wallParallelX) + (rayY * wallParallelY))/(
    (vectorX * wallParallelX) + (vectorY * wallParallelY)
)
if (
    (math.min(v[1],v[3]) <= (cam.x + (Distance * vectorX)) and math.max(v[1],v[3]) >= (cam.x + (Distance * vectorX))) and
        (math.min(v[2],v[4]) <= (cam.y + (Distance * vectorY)) and math.max(v[2],v[4]) >= (cam.y + (Distance * vectorY)))
) then
    table.insert(possibles, Distance)
else
    table.insert(possibles, 0)
end

这段代码从帖子的回答转换为Lua,但是当绘制光线时,它们看起来断断续续的,像这样:

异常光线投射

我做了调试和检查,结果发现当光线被检测是否与直线相交时,返回值为0(返回值为0表示光线似乎没有与墙壁相交)。正如你看到的,墙上确实有墙体,左上角的小地图就显示了这一点。

为什么当光线相交时没有被检测到?如果有不理解的地方,请问。

r = 光线的角度

v = 列表的一个索引 {}; v[i] 是线的x1、y1、x2、y2之一

点赞