0
\$\begingroup\$

When I move it it obviously changes the viewport so my mouse picking is off.

My camera is just a float x and y and I use g.translate(-cam.cameraX+400, -cam.cameraY+300); to translate the graphics. I have the numbers hard coded just for testing purposes.

How would I take into account the camera so my mouse picking works correctly.

double mousetileX = Math.floor((double)mouseX/tiles.tileWidth);
    double mousetileY = Math.floor((double)mouseY/tiles.tileHeight);

    double playertileX = Math.floor(playerX/tiles.tileWidth);
    double playertileY = Math.floor(playerY/tiles.tileHeight);

    double lengthX = Math.abs((float)playertileX - mousetileX); 
    double lengthY = Math.abs((float)playertileY - mousetileY);
    double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY)); 

    if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) { 
        if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) {
            tiles.map[(int)mousetileX][(int)mousetileY] = 0;
        }
    } 

That is my mouse picking code

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

To get back to world-space, you need to reverse your translation from graphics. Think of graphics-space as U and V instead of X and Y:

u = x + (400 - cameraX); // X coord in graphics space
v = y + (300 - cameraY); // Y coord in graphics space

So to reverse this, rearrange for x and y:

x = u - (400 - cameraX);
y = v - (300 - cameraY);
\$\endgroup\$
2
  • \$\begingroup\$ Where exactly do I use this? And every time I use a variable with coordinates do I have to subtract this from it? Can you give me an example of a variable using this \$\endgroup\$
    – Corey
    Jul 10, 2012 at 17:39
  • \$\begingroup\$ You'd need to do this if you were translating screen co-ordinates (i.e, from mouse picking) to world co-ordinates. Because you move the things when going from world to screen, you only need to reverse it when going from screen to world - in other words, when trying to align some point on the user's monitor to some point in the game world. \$\endgroup\$
    – Matt Kemp
    Jul 10, 2012 at 20:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .