Hey guys,
I’ve recently tried making a maze game using 2d arrays. I know this might not be the best way but I’m trying to keep doing this way. Could anyone help me understand why the first wall in the array is registered but every wall after that isn’t? The collision works perfectly fine on the first wall, but not for the others. Help?
CODE:
int [][] wallsArray = {{400,50,50,750},{295,0,50,325}};
int numberWalls = wallsArray.length*2;
int [] xArray = new int [numberWalls];
int [] yArray = new int[numberWalls];
float leftright;
float updown;
float dir = 2;
int flag;
void setup(){
size(800,800);
}
void draw(){
background(0);
rect(leftright,updown,50,50);
//Drawing the walls
for(int i = 0; i < wallsArray.length; i++){
rect(wallsArray[i][0],wallsArray[i][1],wallsArray[i][2],wallsArray[i][3]);
}
//Creating an Array for the x values and a serperate array for the y values of the walls.
for(int i = 0; i < wallsArray.length; i++){
xArray[i*2] = wallsArray[i][0];
xArray[(i2)+1] = (wallsArray[i][0]+wallsArray[i][2]);
yArray[i*2] = wallsArray[i][1];
yArray[(i2)+1] = (wallsArray[i][1]+wallsArray[i][3]);
}
//If key pressed, go that direction.
if (keyPressed){
if (key ==‘s’){
updown = updown + dir;
flag = 1;
}
if(key == ‘w’){
updown = updown - dir;
flag = 2;
}
if(key == ‘a’){
leftright = leftright - dir;
flag = 3;
}
if(key == ‘d’){
leftright = leftright + dir;
flag = 4;
}
//Checking if position, about to be moved to, is inside the walls.
for(int i = 0; i < wallsArray.length; i++){
if(((leftright+50) > xArray[i]) && (leftright < xArray[(i+1)])){
if(((updown+50) > yArray[i]) && (updown < yArray[(i+1)]))
{
//if position is inside walls, using the flag from keypressed, move the opposite direction to stop it from going into the wall.
switch(flag) {
case 1:
updown = updown - dir;
break;
case 2:
updown = updown + dir;
break;
case 3:
leftright = leftright + dir;
break;
case 4:
leftright = leftright - dir;
break;
}
}
}
}
}
leftright = constrain(leftright,0,750);
updown = constrain(updown,0,750);
}
Thanks,
Burakkuboido