0
\$\begingroup\$

I am using a tilemap in which I have square tiles.
Knowing that, the size of the screen and the player position(in world coordinates) how I convert between this systems? Is there any formula?

EDIT:
For example:

The top left corner is (0,0)
player position in tiles: (ScreenX / 2, ScreenY / 2)
player position in screen: always (0, 0)
grass tile position in tiles: (Gx, Gy)

Now the question is: how can I get the screen coordinates for the grass tile?

\$\endgroup\$
  • \$\begingroup\$ What do you mean with "world coordinates"? Give us an example so we can think something \$\endgroup\$ – Juanpa Jan 23 '19 at 21:02
1
\$\begingroup\$

If your grass tile's position in the tilemap is <Gx,Gy> then its pixel position in the game world will be:

tile_worldX = Gx * Tile_Size
tile_worldY = Gy * Tile_Size

Then you subtract the position of the screen's top-left corner from these coordinates to get their on-screen pixel position:

tile_screenX = tile_worldX - view_x
tile_screenY = tile_worldY - view_y

This assumes that the screen's top-left corner is 0,0 in your viewport. Sometimes game engines will move 0,0 to the middle or bottom-left of the viewport so you may have to compensate for that difference.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Hello, thanks for your response but I still can't get this right. This is code to get the screen coordinates(I am using pygame): pygame.Rect(math.floor(3 / TILESIZE), math.floor(2 / TILESIZE), self.ts, self.ts), The world coordinates are (3, 2) \$\endgroup\$ – Simple coder Jan 24 '19 at 17:26
  • \$\begingroup\$ Can you clarify that (3,2) refers to the rows and columns in your tilemap? I believe you would need to multiply those numbers by the tile size to get the pixel coordinates. So X = Tile_Column * Tile_Size and Y = Tile_Row * Tile_Size \$\endgroup\$ – Romen Jan 24 '19 at 17:30
  • \$\begingroup\$ Okay, your player is always at 0,0 on screen; Is that the top-left corner or the middle of the screen? \$\endgroup\$ – Romen Jan 24 '19 at 17:36
  • \$\begingroup\$ I reedited the question, sorry \$\endgroup\$ – Simple coder Jan 24 '19 at 17:53
  • \$\begingroup\$ Hello, thanks for your massive help! I now have it working, I used this: math.floor(Gx * TILESIZE) + math.floor(self.Px * TILESIZE). Feel free to update your answer to include this, but anyway I will accept it. Thanks again! \$\endgroup\$ – Simple coder Jan 24 '19 at 19:30

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.