屏幕坐标到等轴坐标

时间:2013-10-31 22:36:40

标签: 2d coordinates projection tile isometric

我正在努力将鼠标/屏幕坐标转换为等距瓷砖索引。我已经尝试了我在这里或在互联网上找到的每一个公式,但它们似乎都没有用,或者我错过了一些东西。 http://i.imgur.com/HnKpYmG.png 这是一张图片,原点位于左上角,一个图块的尺寸为128x64px。

感谢您的帮助,谢谢。

2 个答案:

答案 0 :(得分:5)

基本上,您需要应用带有一些其他位的旋转矩阵。这是一些用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;
}

我用几个不同的坐标测试了它,结果似乎是正确的。

答案 1 :(得分:0)

我尝试了acfrancis的解决方案,我发现该功能在负指数方面有其局限性。以防万一其他人将解决此问题: 问题原因:负值如-0.1 ....将被强制转换为0而不是-1。 它的经典"只有一个零"数组的问题。

要解决它:在将x2,y2值转换为int之前: 检查是否xr / diag< 0,如果为真,则结果=结果 - 1 (分别对于y2:yr * -1 / diag< 0然后结果=结果-1) 然后将结果值转换为int,就像之前一样。

希望它有所帮助。

增加: 128 * 5的原点翻译似乎特定于某种情况,所以我想这应该被删除以便推广该功能。

相关问题