I have been working on a 2D game, kind of like Terraria, and i have got to the stage where i am ready to do collision detection. I tried it myself, but it... well, its very strange. I was wondering if anybody could help me with this. I store all of my blocks in a 2D array:
Block[][] map = new Block[mw][mh];
where mw
is map width and mh
is map height (in terms of number of blocks). Each Block
is an image that is displayed as 16x16 pixels. Here is what i attempted, i know that it is wrong but i dont really know what i need to do.
private void checkCollision() {
for(int x = -1; x <= 1; x++){
for(int y = -1; y <= 2; y++){
Rectangle obj = new Rectangle((int)Block.getXOnScreen(xblock+x), (int)Block.getYOnScreen(yblock+y), 16, 16);
try{
if(main.map[(int) (xblock+x)][(int) (yblock+y)].solid && obj.intersects(bounds()){
if(y <= -1 && velY > 0){
velY = 0;
System.out.println("Collision below");
onground = true;
}else if(y >= 2 && velY < 0){
velY = 0;
System.out.println("Collision above");
}
if(x <= -1 && velX < 0){
velX = 0;
System.out.println("Collision left");
}else if(x >= 1 && velX > 0){
velX = 0;
System.out.println("Collision right");
}
}
}catch(Exception e){}
}
}
}
I call this method every tick like so, but it doesn't collide with anything so the player just falls.
public void tick(){
xblock += velX;
yblock += velY;
velY += gravity;
checkCollision();
}
If anyone knows how to do collision detection efficiently please can you share this with me. Thanks! :)