im trying to do collision detection with world based on tilemaps (two dimensional array) array -
private int WIDTH = 10;
private int HEIGHT = 6;
String[][] simplemap = new String[][]{
{ "0","1","2","3","4","5","6","7","8","g",},
{ "11","g","","","","","g","","","g",},
{ "22","g","","","","","g","","","g",},
{ "33","g","","","","","g","","","g",},
{ "44","g","","","","","g","","","g",},
{ "g","g","g","g","g","g","g","g","g","g",},
{ "g","g","g","g","g","g","g","g","g","g",},
};
than i create array from blocks and trying to show it
create blocks :
blocks = new Enemy[HEIGHT][WIDTH];
for(int i =0;i<HEIGHT;i++){
for(int j=0;j<WIDTH;j++){
blocks[i][j]= new Enemy(context,0,0);
blocks[i][j].boxWidth=blockWidth;
blocks[i][j].boxHeight=blockHeight;
blocks[i][j].x=blockWidth*j;
blocks[i][j].y=blockHeight*i;
blocks[i][j].state = simplemap[i][j];
}
}
im not sure about
blocks[i][j].x=blockWidth*j;
blocks[i][j].y=blockHeight*i;
but if write blockWidth*i (not j) than map building like rotated on 90 degree. Maybe error here in this code. Not sure Than in glDraw i draw my map
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if ( blocks[i][j].state == "g") {
blocks[i][j].draw(gl);
}
}
}
For collision i do a this code (it's for Y collision detection) for X collision code similar
for(int i = (int)ball.y/tileSize; i<(ball.y+ball.boxWidth)/tileSize; i++) {
for(int j = (int)ball.x/tileSize; j<(ball.x+ball.boxWidth)/tileSize;j++) {
//System.out.print(" i = "+i+"j "+j);
Log.e("ERROR ", " "+i+":"+j);
Log.e("ERROR", "DY = "+dy);
if (blocks[i][j].state=="g") {
//do what we need, check directions or something other
}
}
}
Problem
Map drawing ok with this code , and my object work only in small area like i =HEIGHT,
In tests its like when i start moving from left to right side - i see 10 blocks(like road) app always crashed with nullpointerexception(from array out of bounds) after 4-5 blocks on road. I think i just not correct building my map and position . With this code i see on phone correct map, if change i and j when we set position for every blocks - than its rounded on 90 degree. Also exception on code if (blocks[i][j].state=="g")
array out of bounds . Length 6 etc. I cant understand where my error, can any good guy help me ? please.
Regards, Peter.
Thank you all guys Not sure if its right - but in test its show all correct; code for collision on Y
public void checkColisionY(){
dy = dy + gravity * dt;
ball.y = ball.y + dy * dt + 0.05f * gravity * dt * dt;
for(int i = (int)ball.y/tileSize; i<(ball.y+ball.boxWidth)/tileSize; i++){
for(int j = (int)ball.x/tileSize; j<(ball.x+ball.boxWidth)/tileSize;j++)
{
if(dy>0){
if(ball.y+ball.boxWidth>=blocks[i+1][j].y && blocks[i+1][j].state =="g"){
ball.y = blocks[i+1][j].y-ball.boxWidth;
dy=dy*energyloss;
dy = dy * -1;
}
}
}
}
}