Drawing visible tiles - side scrolling
- by Troubleshoot
Currently I'm calling drawMap every time repaint is called. This is the code I've written for my drawMap method so far.
public void drawMap(Graphics2D g2d) {
float cameraX = Player.getX() - (Frame.CANVAS_WIDTH / 2);
float cameraY = Player.getY() - (Frame.CANVAS_HEIGHT / 2);
int tileX = (int) cameraX;
int tileY = (int) cameraY;
int xIndent = 0, yIndent = 0;
int a = 0, b = 0;
while (tileX % TILE_SIZE != 0) {
tileX--;
xIndent++;
}
while (tileY % TILE_SIZE != 0) {
tileY--;
yIndent++;
}
for (int y = tileY; y < tileY + Frame.CANVAS_HEIGHT; y += Map.TILE_SIZE) {
for (int x = tileX; x < tileX + Frame.CANVAS_WIDTH; x += Map.TILE_SIZE) {
if ((y / TILE_SIZE < 0 || x / TILE_SIZE < 0)
|| (y / TILE_SIZE > columnSize))
break;
g2d.drawImage(map[y / TILE_SIZE][x / TILE_SIZE], a - xIndent, b
- yIndent, null);
a += TILE_SIZE;
}
a = 0;
b += TILE_SIZE;
}
}
The idea behind this is that it gets the camera position and draws the map relative to the player position. However, instead of the player being in the center of the screen all the time, the player actually moves away from the center as it scrolls to the right, and moves towards to center as it scrolls to the left. I've been trying to pinpoint what I've done wrong but I can't seem to find it. My code also seems quite messy, so am I doing this the correct way?