Collision checking problem on a Tiled map

Posted by nosferat on Game Development See other posts from Game Development or by nosferat
Published on 2012-11-22T08:47:51Z Indexed on 2012/11/22 11:15 UTC
Read the original article Hit count: 237

I'm working on a pacman styled dungeon crawler, using the free oryx sprites. I've created the map using Tiled, separating the floor, walls and treasure in three different layers. After importing the map in libGDX, it renders fine. I also added the player character, for now it just moves into one direction, the player cannot control it yet. I wanted to add collision and I was planning to do this by checking if the player's new position is on a wall tile. Therefore as you can see in the following code snippet, I get the tile type of the appropriate tile and if it is not zero (since on that layer there is nothing except the wall tile) it is a collision and the player cannot move further:

final Vector2 newPos = charController.move(warrior.getX(), warrior.getY());
if(!collided(newPos)) {
    warrior.setPosition(newPos.x, newPos.y);
    warrior.flip(charController.flipX(), charController.flipY());
}

[..]

private boolean collided(Vector2 newPos) {
    int row = (int) Math.floor((newPos.x / 32));
    int col = (int) Math.floor((newPos.y / 32));

    int tileType = tiledMap.layers.get(1).tiles[row][col];
    if (tileType == 0) {
        return false;
    }

    return true;
}

The character only moves one tile with this code:

Only one tile

If I reduce the col value by two it two more tiles. I think the problem will be around indexing, but I'm totally confused because the zero in the coordinate system of libGDX is in the bottom left corner of the screen, and I don't know the tiles array's indexing is similair or not. The size of the map is 19x21 tiles and looks like the following (the starting position of the player is marked with blue:

The whole map

© Game Development or respective owner

Related posts about java

Related posts about collision-detection