所以我已经做了一个星期了,谷歌搜索和所有的,但我还没有找到如何做到这一点。
我有一张“射线”的桌子和一张“线”的桌子,我想让这些线在光线碰到一条线时就像镜子一样反射光线。想象一下,激光从镜子上反射出来,那种反射。我已经开始做交点检测了,但是我想不出如何正确地计算反射角度,以及如何把光线扩展到这个方向。
代码:
--the table rays is a table of tables, and each table inside is formatted as such:
--rays[x] = {100,200,150,600,200,400}, where (100,200) are ordered pairs, etc.
--The table lines simply contains values for x1,y1,x2,y2
for i,ray in ipairs(rays) do
for j,line in ipairs(lines) do
if line.x2 ~= nil and #ray>3 then
print(line.x2..' '..line.y2)
iX, iY = intersect.test(ray[#ray-3],ray[#ray-2],
ray[#ray-1],ray[#ray],line.x1,line.y1,line.x2,line.y2)
--The above code takes each ray and
--sees if it intersects with a line, with the intersect.test function
--Then if it does, where iX and iY aren't nil, it continues
if iX ~= nil and iY ~= nil then
local rayA = (180/math.pi)*math.atan(getSlope(ray[#ray-3],ray[#ray-2],ray[#ray-1],ray[#ray]))
local lineA = (180/math.pi)*math.atan(getSlope(line.x1,line.y1,line.x2,line.y2))
local normalA = (180/math.pi)*math.atan(-1/getSlope(line.x1,line.y1,line.x2,line.y2))
--Here I'm calculating the angle in degrees. For the final code all those atans will
--be out of there for optimization, but its easiest now to see the actual angle
print(rayA..' '..lineA..' '..normalA)
ray[#ray-1]=iX
ray[#ray]=iY
--This little part just create a point on the ray right at the intersection
--The code after this is my attempt, which doesn't work
local reflectA = normalA-rayA
local reflectR = 2*reflectA+rayA
print(reflectR)
reflectR = reflectR/(180/math.pi)
local rSlope = math.tan(reflectR)
local offset = 0
ray[#ray+1]=iX+offset
ray[#ray+1]=iY+(offset*rSlope)
end
end
end
end我被困在最后一段了。它创造了一个从线上反弹的段,但有时它会越过线,它永远不是正确的反射角。任何关于我应该如何做到这一点的建议都将不胜感激。
发布于 2015-06-22 01:37:45
如果可以避免使用斜率和角度,最好避免它们,因为您将不得不处理恼人的特殊情况,比如斜率为+ve或-ve无穷大等等。
如果可以计算直线的法线(蓝色箭头),则可以使用点积进行反射:

计算这一行的正常值如下所示:
local normalY = line.x2 - line.x1
local normalX = line.y1 - line.y2
local normalLength = math.sqrt(normalX * normalX + normalY * normalY)
normalX = normalX / normalLength
normalY = normalY / normalLength然后,您需要计算从直线和射线的交点到射线尖端的向量(“穿过”要反射的直线的点):
local rayX = rayTipX - iX
local rayY = rayTipY - iY然后计算点积:
local dotProduct = (rayX * normalX) + (rayY * normalY)这告诉我们,射线在正常的直线方向上有多远,已经通过了交点(绿线的长度)。若要找到绿色线的矢量,请将法向线乘以点积:
local dotNormalX = dotProduct * normalX
local dotNormalY = dotProduct * normalY如果我们否定这个向量,然后加倍它(得到绿线加上粉红线),然后把它加到射线的顶端,我们将得到射线的反射尖端:
local reflectedRayTipX = rayTipX - (dotNormalX * 2)
local reflectedRayTipY = rayTipY - (dotNormalY * 2)https://stackoverflow.com/questions/30970103
复制相似问题