I've asked on gamedev.stackexchange too, but so far I have no answer. You can read the stackexchange question here. It contains details. I will write a short version here.
Here's the code I have for drawing the tiles
// Draw code
int col = 0;
int row = 0;
for (int i = 0; i < nrOfTiles; ++i)
{
// XOffset and YOffset are currently hardcoded values, but will represent camera offset combined with HUD offset
Point tile = IsoToScreen(col, row, TileWidth / 2, TileHeight / 2, XOffset, YOffset);
int x = tile.X;
int y = tile.Y;
spriteBatch.Draw(_tiles, new Rectangle(tile.X, tile.Y, TileWidth, TileHeight), Color.White);
col++;
if (col >= Columns) // Columns is the number of tiles in a single row
{
col = 0;
row++;
}
}
// Get selection overlay location (removed check if selection exists for simplicity sake)
Point tile = IsoToScreen(_selectedTile.X, _selectedTile.Y, TileWidth / 2, TileHeight / 2, XOffset, YOffset);
spriteBatch.Draw(_selectionTexture, new Rectangle(tile.X, tile.Y, TileWidth, TileHeight), Color.White);
// End of draw code
public Point IsoToScreen(int isoX, int isoY, int widthHalf, int heightHalf, int xOffset, int yOffset)
{
Point newPoint = new Point();
newPoint.X = widthHalf * (isoX + isoY) + xOffset;
newPoint.Y = heightHalf * (-isoX + isoY) + yOffset;
return newPoint;
}
And here is the code for getting which tile is the mouse on
public Point? ScreenToIso(int screenX, int screenY, int tileHeight, int offsetX, int offsetY)
{
Point? newPoint = null;
int nX = -1;
int nY = -1;
int tX = screenX - offsetX;
int tY = screenY - offsetY;
nX = -(tY - tX / 2) / tileHeight;
nY = (tY + tX / 2) / tileHeight;
newPoint = new Point(nX, nY);
return newPoint;
}
This code is close, but not even close enough for a public beta or something like that (even though this is just a proof of concept, which I will later transform into my game). I have no idea why this code is so close. I drew the tiles by thinking up the formula, and by googling I believe I've seen that it is correct (however it's still possible it's not). The code for picking - what ever I came up with, didn't work. What ever I googled, didn't work. This code I currently have is a derivation of something I googled - it was not really close, but closer than others, so I modified it and it's even closer now - I did it by trial and error as I have no idea behaved and behaves the way it did/does.
Can anyone point out to me my error? Whenever I think about it, it doesn't make sense to me that it behaves that way. I tried reversing the formula for drawing and it didn't pan out which doesn't make sense either. I must be doing something wrong then so please, if someone sees my error, could you point it out?