2013-10-31 186 views
0

我很努力將鼠標/屏幕座標轉換爲等軸測圖塊索引。我嘗試了一下我可以在這裏或互聯網上找到的每一個配方,但是它們都不起作用,或者我缺少一些東西。 http://i.imgur.com/HnKpYmG.png 這是一張圖片,原點位於左上角,一個圖塊的尺寸爲128x64px。屏幕座標到等距座標

我將不勝感激任何幫助,謝謝。

回答

3

基本上,你需要應用一個旋轉矩陣和其他一些位。下面是寫在AWK一些示例代碼,這應該是很容易移植到任何其他語言:

END { 
    PI = 3.1415; 
    x = 878.0; 
    y = 158.0; 

    # Translate one origin to the other 
    x1 = x - 128*5; 
    # Stretch the height so that it's the same as the width in the isometric 
    # This makes the rotation easier 
    # Invert the sign because y is upwards in math but downwards in graphics 
    y1 = y * -2; 

    # Apply a counter-clockwise rotation of 45 degrees 
    xr = cos(PI/4)*x1 - sin(PI/4)*y1; 
    yr = sin(PI/4)*x1 + cos(PI/4)*y1; 

    # The side of each isometric tile (which is now a square after the stretch) 
    diag = 64 * sqrt(2); 
    # Calculate which tile the coordinate belongs to 
    x2 = int(xr/diag); 
    # Don't forget to invert the sign again 
    y2 = int(yr * -1/diag); 

    # See the final result 
    print x2, y2; 
} 

我用幾個不同的座標系進行了測試,結果似乎是正確的。

+0

工作完美無缺謝謝你。 – Hnus

+0

太棒了,如果你對此感到滿意,不要忘記接受答案。 – acfrancis

+1

挑剔的評論。 PI的第四個小數位在實踐中無關緊要,但您應該正確:3.14159 ...到3.1416。 –

0

我嘗試了acfrancis的解決方案,發現該函數在負指數方面有其侷限性。以防萬一別人解決這個問題: 問題的原因:像-0.1 ....這樣的負值將被轉換爲0而不是-1。 它是數組的經典「只有一個零」問題。

爲了解決它:鑄造前X2,Y2值INT: 檢查,如果XR /診斷< 0,如果爲真,結果=結果 - 1 (分別爲Y2:YR * -1 /診斷< 0然後結果=結果-1) 然後你像以前一樣將結果值轉換爲int。

希望它有幫助。

此外: 由128 * 5的原點翻譯似乎具體到某種情況下,所以我想這應該被刪除,以推廣的功能。