0
\$\begingroup\$

How do I create a 2D tile map that I can use? How do I get the world coordinates of it so I can move something to that tile?

I'm learning OpenGL, at the moment, but I'm having a lot of issues understanding how to create a 2D tile map. I have rendered tiles to the world, but I have no way of using them. For example, I'm trying to implement movement, where when clicking on a tile, I would move the player to that tile.

To elaborate, I want a tiles coordinates when I click near/on it, so I can use that position when implementing movement. Right now, I have no idea how to do that; I am able to get the windows 2D coordinates on click, but I don't know how to turn that into a useful way of finding the coordinates I want based on where my tile is in the world.

\$\endgroup\$
  • \$\begingroup\$ Your question isn't very clear. What do you mean by a 2D tile map that you can "use"? \$\endgroup\$ – Accumulator Apr 20 '17 at 20:16
  • \$\begingroup\$ Sorry, I don't think I fully understand what it is I'm doing. I'm looking for pointers. I want a tile's coordinates when I click near/on it so I can use that when implementing movement. Right now I have no idea how to do that; I am able to get the window's 2d coordinates on click, but I don't know how to turn that into a useful way of finding the coordinate I want. \$\endgroup\$ – Akrilla Apr 20 '17 at 21:02
0
\$\begingroup\$

If you want to be able to get the position of a clicked tile: Store the tiles in a 2D array/vector. Assuming you use 16x16 tiles, divide and floor the mouse position by 16 to get the location in the 2D array of the tile.

\$\endgroup\$
  • \$\begingroup\$ This won't work as not all the tiles are on the screen. The top left tile won't be the first in the array, just like the bottom right wouldn't be the last one. \$\endgroup\$ – Akrilla Apr 20 '17 at 21:21
  • 1
    \$\begingroup\$ Add the camera position to the mouse position. \$\endgroup\$ – Accumulator Apr 20 '17 at 21:23
  • \$\begingroup\$ The complete answer is to apply the inverse projection/view operations to the mouse coordinates (e.g., the inverse matrix, if you have one). That will convert screen coordinates to world coordinates. Handles scale (zoom), rotation, and translation (movement). \$\endgroup\$ – Sean Middleditch Apr 20 '17 at 22:23
  • \$\begingroup\$ Thanks Sean, I thought it was something like that, that makes sense. I can also try and implement Accumulator's solution too. \$\endgroup\$ – Akrilla Apr 21 '17 at 19:51

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.