2
\$\begingroup\$

I'm writing a function that allows me to click on my tiles. The origin for my tiles is the center, however, the mouse's origin is the top left. I need a way to transform my mouse coordinates into my tile coordinates.

Here is what I already have (but is not working):

void mouseClick(int button, int state, int x, int y)
{
    x -= 400;
    y -= 300;
    float xx = x / 100; // This gets me close but the number is still high.
    float yy = y / 100; // It needs to be between -1 and 1
}
\$\endgroup\$
1
  • \$\begingroup\$ Your formula needs to include the size of the window and the size of your tiles. \$\endgroup\$
    – Philipp
    Jun 3 '14 at 15:27
6
\$\begingroup\$

Your description is a bit vague, but it sounds like what you're trying to do is map coordinates from one space (the window coordinates) to another (your tile coordinate space). Doing so is a simple transformation using the window size:

x_trans = x - (windowWidth / 2);
y_trans = y - (windowHeight / 2);
x_norm = x / (windowWidth / 2);
y_norm = y / (windowHeight / 2);

x_trans and y_trans are the x and y coordinates of your mouse click transformed into the coordinate space where the center of the window is 0,0. x_norm and y_norm are the "normalized" (normalized would ordinarily mean [0,1]) coordinates, in a [-1,1] range.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, that is perfect. Sorry about the description. \$\endgroup\$
    – bbdude95
    May 28 '14 at 18:55
2
\$\begingroup\$

You need to know the width and height of the window. How to do this depends on your platform, but I will use "WindowWidth" and "WindowHeight" as placeholders.

void mouseClick(int button, int state, int x, int y)
{
    float xx = x / (WindowWidth / 2.0f);  // This will give a value from 0 - 2
    float yy = y / (WindowHeight / 2.0f);  // This will give a value from 0 - 2
    xx -= 1.0f; // Subtract 1 to get a value from -1 to 1.
    yy -= 1.0f; // Subtract 1 to get a value from -1 to 1.
}
\$\endgroup\$

You must log in to answer this question.

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