2010-02-22 100 views
1

Problem illustration http://i49.tinypic.com/2iui4g.jpg如何給定的矩形內識別子三角形在該矩形

鑑於寬度w和高度h的矩形的座標。以及該矩形中的座標x,y,我想確定我在哪個三角形內。 (0,A,1 = B,2 = C,3 = D) ),如果他們是在這個順序。

我認爲這應該像> =紅線的公式和> =綠線的公式?

我想實現這個在VB.NET

+0

如果是這樣的功課,然後請其標記爲這樣的(它不會停止的答案)。 – Richard 2010-02-22 12:29:04

+0

它不是作業,而是更大問題的一部分:http://stackoverflow.com/questions/2310334/texture-coordinate-mapping-how-to-map-coordinates-of-4-triangles-in-a-square- to-4 – PeanutPower 2010-02-22 12:31:40

回答

6
aboveRed = x*h > y*w; 
aboveGreen = (w-x)*h > y*w; 
if (aboveRed) 
{ 
    if (aboveGreen) return "C"; else return "B"; 
} 
else 
{ 
    if (aboveGreen) return "D"; else return "A"; 
} 
+0

ahh這看起來不錯 – PeanutPower 2010-02-22 12:37:18

1

我會考慮線的角度,從左上角和右上角的點。如果它在兩種情況下都小於45度(調整邊緣的基本方向),則點位於C.其他組合將覆蓋其他三個三角形。

你實際上並不需要計算反向三角函數來完成這個任務,因爲線長度的比例給你足夠的信息(和sin(45)...或者sin(pi/4)是一個固定值)。

3

式綠線:h * x + w * y = h * w

式的紅線:x * h - y * w = 0

Public Function GetTriangleNumber(ByVal x As Integer, ByVal y As Integer) 
                    As Integer 
    Dim overGreenLine As Boolean = ((((h * x) + (w * y)) - (h * w)) < 0) 
    Dim overRedLine As Boolean = (((h * x) - (w * y)) > 0) 
    If overGreenLine Then 
     Return IIf(overRedLine, 2, 3) 
    End If 
    Return IIf(overRedLine, 1, 0) 
End Function 
+0

謝謝我給了VB代碼的upvote,但接受了Vlad的答案,因爲他首先使用算法 – PeanutPower 2010-02-22 12:45:57