0
votes

I'm making a game in Processing.js. When I zoom in on my game world, the mouse position is the game world is obviously offset. How do I get it so the mouse position is relative to the position in the game world, not the top left of the screen(0,0) after using scale(x,y) to zoom relative to the top left? Here is my code so far, complete with movement and zooming. All I need is some way to find the in game mouse position so I can click to place circles anywhere in the map.

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 
1

1 Answers

1
votes

I figured it out! Here is the code to add a circle in a scaled and translated world based on mouse position:

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

Essentially, I am multiplying x by zoom and y by zoom, and add mouse x and y divided by the zoom to the previous results divided by the zoom. Last, I am subtracting width/2,/zoom to center everything. Hope this helps!