2
votes

I'm working on a isometric game and have trouble making a tile selection algorithm.

This is how I render my isometric tilemap :

for (int x = 0; x < 50; x++) {
    for (int y = 0; y < 50; y++) {
        //Check if tile should be drawn
        if (mapdata[x][y] == 1) {
            float px = (x - y) * 20;
            float py = (x + y) * 20 / 2;

            ...

            window.draw(quad, &tile);
        } 
    }
}

I use a 2d array to store which tiles should be drawn. example:

int mapdata[5][5]
{
    0,1,1,1,0,
    0,1,1,1,0,
    0,1,1,1,0,
    0,1,1,1,0,
    0,1,1,1,0,
}

This is how I currently 'select' tiles :

mh = the map tile height, in the above example this would be 5.
w = the width of the isometric tile.

int mouse_grid_y = (((mousey * 2) - ((mh * w) / 2) + mousex) / 2) / w;
int mouse_grid_x = (mousex - mouse_grid_y) / w;

Any help would be greatly appreciated.

Image to clarify :

This is an image I made for my game tutorial. As you can see there is one tile outlined with green, this is what I need the algorithm for, I want to track the mouse, and draw this green 'cursor' over the tile where the mouse is.

img example

1
Can you clarify the question a bit more please?Rietty
I want to calculate on which tile in the grid the mouse cursor is inside the game in window. I can add an image if you want.Justbod
In OpenGL, that's called picking.Neil
Ah, okay! I will edit the title :)Justbod
What result do you get with your current code? How does the quad that you draw look like (where is its origin?) How are you obtaining the mouse position? Is this already in the same space as the draw locations? Why is there no 20 in the selection code? Is this w?Nico Schertler

1 Answers

2
votes

You can transform screen coordinates into your local system making reverse calculation:

xx = px - basex
yy = py - basey
x' = (xx + 2 * yy) / 40   // integer division to get cell index
y' = (-xx  + 2 * yy) / 40

basex and basey are coordinates of starting point at your screen, where cell 0,0 is drawn (is not mentioned in your question)