Drawing visible tiles - side scrolling

Posted by Troubleshoot on Game Development See other posts from Game Development or by Troubleshoot
Published on 2013-10-20T12:38:11Z Indexed on 2013/10/20 16:12 UTC
Read the original article Hit count: 238

Filed under:
|
|

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?

© Game Development or respective owner

Related posts about java

Related posts about tilemap