首页 > 解决方案 > 在翻译的游戏世界中获取鼠标位置:processing.js

问题描述

我正在 Processing.js 中制作游戏。当我放大我的游戏世界时,鼠标位置是游戏世界明显偏移。如何获得它,以便鼠标位置相对于游戏世界中的位置,而不是使用 scale(x,y) 相对于左上角缩放后屏幕的左上角(0,0)?到目前为止,这是我的代码,包括移动和缩放。我所需要的只是找到游戏中鼠标位置的方法,这样我就可以单击以在地图中的任何位置放置圆圈。

pushMatrix();
translate(-pos.x*zoom+width/2, -pos.y*zoom+height/2);
scale(zoom);
for(var i = 0; i<circles.length; i++){
    circles[i].update();
}
if(clicked){
    circles.push(new Circle(mouseX-width/2,mouseY-width/2));//should i have this inside the translation? Outside? coordinates so far only work when zoom is 1 and pos.x and pos.y arent changed
}
popMatrix();//end of translation 

标签: javascripthtml5-canvasprocessing

解决方案


我想到了!这是根据鼠标位置在缩放和平移的世界中添加圆圈的代码:

circles.push(new Circle((pos.x*zoom+mouseX-width/2)/zoom,(pos.y*zoom+mouseY-height/2)/zoom))

本质上,我将 x 乘以缩放和 y 乘以缩放,并将鼠标 x 和 y 除以缩放添加到先前的结果除以缩放。最后,我减去 width/2,/zoom 以使所有内容居中。希望这可以帮助!


推荐阅读