Get Isometric Tile Under Mouse

610 views Asked by At

Ok, so I have my isometric map where the width of each tile is 64 and the height is 32. This is the equation I came up with to place the tiles

xPos = (this.getPos().getX() - this.getPos().getY()) * (64 / 2) - Main.gameWindow.getCamera().getxOffset().intValue();
xPos -= 32;
yPos = (this.getPos().getX() + this.getPos().getY()) * (32 / 2) - Main.gameWindow.getCamera().getyOffset().intValue();

I subtract xPos by 32 to make up for the fact that the origin point of the tile is in the far left corner.

What I've been trying to do is find the tile that is beneath my mouse. So first I tried simply reversing the equation (I was sure it would work) And this is the code I ended up with when I reversed it.

int yMouseTile = ( (cursorY / (32 / 2) - (cursorX / 32)) / 2 );
int xMouseTile = ( (cursorX / 32) + yMouseTile);

This only sort of works. But as it turns out, this code actually treats each tile as if it were a square, not a diamond.

The next weird part is that when my mouse passes over the center of the tile, the tile changes. So what should happen, is that my mouse should go over the edge of the tile, and then it changes to the next one. But instead, it acts as if the center of tile is actually the edge.

But really, all I want is the equation that will cause my mouse to work like this http://www.tonypa.pri.ee/tbw/tut18.html

On that link, click the "Click Here to Start" Button, and watch how the mouse interacts with the tiles. That is my goal :), thanks

P.S. I've tried a myriad of different equations, many of which have the exact same result as the equation I have above

1

There are 1 answers

4
James Newman On

Refactor your variable names.

int TILE_WIDTH = 64;
int TILE_HEIGHT = TILE_WIDTH / 2;

int xMap = this.getPos().getX();
int yMap = this.getPos().getY();

int xScreenCameraOffset = Main.gameWindow.getCamera().getxOffset().intValue();
int yScreenCameraOffset = Main.gameWindow.getCamera().getyOffset().intValue();

xScreen = (xMap - yMap) * (TILE_WIDTH / 2) - yScreenCameraOffset;
yScreen = (xMap + yMap) * (TILE_HEIGHT / 2) - yScreenCameraOffset;

This might seem excessive, but in my opinion is way easier to read and reason about. According to this tutorial If you try to derive The reverse equation you would get:

xMouseTile = (xCursor / TILE_WIDTH  / 2 + yCursor / TILE_HEIGHT / 2) / 2;
yMouseTile = (yCursor / TILE_HEIGHT / 2 - xCursor / TILE_WIDTH  / 2) / 2;

This doesn't take into account the camera offset.