Tuesday, January 23, 2018

tiles - Isometric rendering and picking?


I've been looking for a formula to plot (world->screen) and mouse pick (world->screen) isometric tiles in a diamond-shaped world. The ones I've tried always seem to be, well, off. What's the usual/correct way to do this?



Answer



Based on your comment, here's the code I'm using to convert tile x,y values to on screen coordinates. Now, it doesn't take into account "3d tiles", everything is considered as being on the same plane, so if you're writing a game where that matters, this code will not work.


//this converts a map x/y coordinate into screen coordinates
//public, static method, so can be called outside the Tile object

point Tile::convertToScreen(int x, int y, int offsetX, int offsetY)
{
point screen;
//calculate the screen coordinates
//note: these will then be modified by the camera
screen.x = offsetX - (y * TILE_WIDTH/2) + (x * TILE_WIDTH/2) - (TILE_WIDTH/2);
screen.y = offsetY + (y * TILE_DEPTH/2) + (x * TILE_DEPTH/2);
return screen;
}


point is simply a structure containing x and y ints, TILE_WIDTH would be 64 in your case, TILE_DEPTH is kind of badly named (it is actually the height of the tile graphics), but it would be 32 in your case. The offsets are if you want your tile map to "start" at a different x,y location (such as if you want tiles to be above another set of tiles). Typically the offset can be 0,0.


This will generate a map with 0,0 on top, middle, like this:


        0,0
0,1 1,0
0,2 1,1 2,1

As for finding the tile x,y of the cursor:


point selectedTile;
int x = mX - camera.x;
int y = mY - camera.y;

selectedTile.x = (y + x/2)/TILE_DEPTH;
selectedTile.y = (y - x/2)/TILE_DEPTH;

In this bit of code, mX and mY are the mouse screen coordinates, which we're combining with the camera values to find out where we are in "world coordinates". Everything else is the same as the previous code example.


Once again, this assumes a flat 2d isometric tile map. There's some additional work if you want to use a semi-3d view of the map, and this all assumes that you're working in 2d anyway.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...