If any one can help me with the bounds checking for my tilemap I would greatly appreciate it.
My tilemap engine works perfectly untill it tries to scroll to the very horizontal or vertical limit. If I scroll by the size of the tiles used then it gets to the xMaxPos (or yMaxPos) position without a hitch. I am therefore assuming that these two values are being calculated correctly.
The problem occurs when I try to scroll to the boundary by a unit less than the tile size or try to scroll away from the boundary when it's at the max position. The progam crashes very ungracefully.
I searched for threads on similar problems and an answer that comes up occasonally is to just add an extra row and column of tiles. I can't figure this out because surely as I approach the max coordinates or leave the max cordinates it disects the last visible tile, which can be displayed with no problems...
Code:
void TileMapLayer::draw(BITMAP *dest) {
int xSrc, ySrc;
int xDest, yDest;
int topTile = xPos / xTileSize;
int leftTile = yPos / yTileSize;
int topTileOffset = xPos % xTileSize;
int leftTileOffset = yPos % yTileSize;
int bottomTile = (int)((xPos + xScreenSize) / (float)xTileSize + 0.5) + ((topTileOffset == 0) ? 0 : 1);
int rightTile = (int)((yPos + yScreenSize) / (float)yTileSize + 0.5) + ((leftTileOffset == 0) ? 0 : 1);
for(xSrc = topTile; xSrc < bottomTile; xSrc++ ) {
for(ySrc = leftTile; ySrc < rightTile; ySrc++ ) {
xDest = (xSrc - topTile) * xTileSize - topTileOffset;
yDest = (ySrc - leftTile) * yTileSize - leftTileOffset;
blit(cell[xSrc][ySrc].image, dest, 0, 0, xDest, yDest, xTileSize, yTileSize);
}
}
}
bool TileMapLayer::scrollUp(int yOffset) {
yPos -= yOffset;
if (yPos < 0) {
yPos = 0;
return false;
}
return true;
}
bool TileMapLayer::scrollDown(int yOffset) {
yPos += yOffset;
if (yPos > yMaxPos - yTileSize) {
yPos = yMaxPos - yTileSize;
return false;
}
return true;
}
bool TileMapLayer::scrollLeft(int xOffset) {
xPos -= xOffset;
if (xPos < 0) {
xPos = 0;
return false;
}
return true;
}
bool TileMapLayer::scrollRight(int xOffset) {
xPos += xOffset;
if (xPos > xMaxPos - xTileSize) {
xPos = xMaxPos - xTileSize;
return false;
}
return true;
}