Java - 2d Array Tile Map Collision

Posted by Corey on Game Development See other posts from Game Development or by Corey
Published on 2012-06-13T02:10:27Z Indexed on 2012/06/13 4:48 UTC
Read the original article Hit count: 385

Filed under:
|
|

How would I go about making certain tiles in my array collide with my player? Like say I want every number 2 in the array to collide. I am reading my array from a txt file if that matters and I am using the slick2d library.

Here is my code if needed.

public class Tiles {

Image[] tiles = new Image[3];

int[][] map = new int[500][500];

Image grass, dirt, mound;

SpriteSheet tileSheet;

int tileWidth = 32;
int tileHeight = 32;

public void init() throws IOException, SlickException {
    tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight);

    grass = tileSheet.getSprite(0, 0);
    dirt = tileSheet.getSprite(7, 7);
    mound = tileSheet.getSprite(2, 6);
    tiles[0] = grass;
    tiles[1] = dirt; 
    tiles[2] = mound;

    int x=0, y=0;
BufferedReader in = new BufferedReader(new FileReader("assets/map.txt"));
String line;
while ((line = in.readLine()) != null) {
        String[] values = line.split(",");
    for (String str : values) {
            int str_int = Integer.parseInt(str);
            map[x][y]=str_int;
            //System.out.print(map[x][y] + " ");
            y=y+1;
        }
//System.out.println("");
x=x+1;
    y = 0;
}
    in.close();
}

public void update() {

}

public void render(GameContainer gc) {
    for(int x = 0; x < 50; x++) {
        for(int y = 0; y < 50; y ++) {
            int textureIndex = map[y][x];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }
}

}

I tried something like this, but I it doesn't ever "collide". X and y are my player position.

if (tiles.map[(int)x/32][(int)y/32] == 2)
    {
        System.out.println("Collided");
    }

© Game Development or respective owner

Related posts about java

Related posts about collision-detection