我认为 for 循环会使事情变得过于复杂。您可以改为编写一些语句来在 和 之间进行screen space
转换board space
。
假设您的屏幕空间是800px
by600px
并且您有一个10 x 10
由二维数组表示的游戏板:board[10][10]
。还假设您开始在10px
偏移处绘制板0,0
并且您的板很500px
宽。在这种情况下,您知道板上每个单元格占用多少屏幕空间:
int boardScreenWidth = 500;
int cellWidth = boardScreenWidth / boardWidth;
// = 500px / 10
// = 50px
首先忽略不接触板的点击:
int boardStartX = 10;
if (mouseX < boardStartX || mouseX >= boardStartX + boardScreenWidth)
return; // The user clicked somewhere to the left or right of the board
然后,如果点击是在棋盘上,您将需要根据棋盘与 0 的偏移量来调整鼠标位置(这样点击x=10px
就如同在x=0
棋盘位置上单击一样)。有了这些信息,就可以很容易地将屏幕空间中的 x 坐标转换为 中的索引board
:
int mouseX = 320; // user clicked at x=320
mouseX = mouseX - boardStartX; // adjust based on board's position
int boardX = mouseX / cellWidth;
// = 310 / 50
// = 6
您可以找到boardY
类似的方法,然后访问在 处单击的单元格board[boardX][boardY]
。
编辑:要从索引中获取屏幕坐标,请board
使用上面相同的逻辑,但要解决mouseX
:
int boardX = (mouseX - boardStartX) / cellWidth;
// ==> boardX * cellWidth = mouseX - boardStartX
// ==> (boardX * cellWidth) + boardStartX = mouseX
// or...
int screenX = boardStartX + (boardX * cellWidth);
请注意,这是单元格的边缘。整个单元格将从screenX
到screenX + cellWidth
。单元格的中心位于screenX + cellWidth / 2