0
\$\begingroup\$

I have a 2D world background made up of a Grid of graphics, which I display on screen with a viewport (800x600) and it all works.

My question is I have the following code to

convert the mouse co-ordinates to world co-ordinates

then

World co-ordinates to grid co-ordinates

then

grid co-ordinates to screen co-ordinates.

//Add camerax to mouse screen co-ords to convert to world co-ords.    
int cursorx_world=(int)camerax+(int)GameInput.mousex;
int cursorx_grid=(int)cursorx_world/blocksize;  // World Co-ords / gridsize give grid co-ords
int cursorx_screen=-(int)camerax+(cursorx_grid*blocksize);

So is there anyway I can convert straight from mouse screen co-ords to screen co-ordinates?

\$\endgroup\$
1
\$\begingroup\$

Something I use fairly often is a viewbounds variable, which is a list of three game coordinates. The first is the upper-left corner of the screen, the second is the center, and the third is the bottom right. I also use zoom (which looks like your blocksize).

When you register a mouse event, you can find its game coordinate by offsetting from the first viewbound by the coordinates of the mouse multiplied** by the zoom level.

// Create a new Coordinate using a copy constructor
game_coor = new Coordinate(viewbounds[0]).add(mouse_coor.multiply(zoom));

** Depending on your implementation zoom could be px/unit or unit/px, multiply or divide accordingly.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.