2015-06-21 115 views
2

所以我一直在這個開關上工作了一個星期,Google搜索和所有,我還沒有找到如何做到這一點。「反射鏡」上的二維線條反射

我有一張「光線」表和一張「線條」表,我希望線條可以作爲鏡子,並在光線碰到線條時反射光線。想象一下激光從鏡子反射回來,那種反射。我有交叉檢測工作,但我無法弄清楚如何正確計算反射角度並延長光線的方向。

代碼:

--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 

我卡上最後一節。它有點創造了一條反彈的線段,但有時它跨越線條,而且它永遠不會是正確的反射角度。任何指示我應該如何做到這一點將不勝感激。

回答

3

如果你能避開它們,避免使用斜坡和角度更好,因爲你將不得不面對惱人的特殊情況,例如坡度爲+ ve或-ve無窮等等。

如果能計算出正常線(藍色箭頭),那麼你可以使用點產品做反思:

enter image description here

計算正常的線路就像下面這樣:

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) 
+2

是的!謝謝,這個作品很棒。 –