So currently I am making a maze game, and of course for it to be a maze game it has to have walls. Walls need to stop the player from going over them. I am having a problem checking for collision. It works in some places, and others not. My current method is going through my 2d array, that finds what number the player is attempting to go on by dividing their current x and y by 50, and then using those two numbers to try and see if the player would be colliding with a wall or not. What is happening is that it stops the player from moving for some walls, and some not. In addition it also stops the player in places where there is no wall (a value where it would be 2). I feel like something is getting messed up with the math, but I can't figure out what. Here is the code for how I make the maze, along with the array it is being made from:
private int[][] mazeWalls = { //top of the maze
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 2, 2, 2, 2, 2, 2, 1, 2, 1},
{1, 2, 2, 2, 2, 2, 2, 1, 2, 1},
{1, 2, 2, 2, 2, 2, 2, 1, 2, 1},
{1, 1, 1, 1, 2, 2, 2, 2, 2, 1},
/*left side*/{1, 2, 2, 2, 2, 2, 2, 2, 2, 1}, //right side
{1, 2, 2, 2, 2, 2, 2, 1, 2, 1},
{1, 2, 2, 2, 2, 2, 2, 1, 2, 1},
{1, 2, 2, 2, 2, 2, 2, 1, 2, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
//bottom of the maze
};
public void paintMaze(Graphics g){
for(int row = 0; row < mazeWalls.length; row++){ //example of loops
for(int col = 0; col < mazeWalls[row].length; col++){ //getting the positions set up
if(mazeWalls[row][col] == 1){
g.setColor(Color.RED); //color of the walls
g.fillRect(col * 50, row * 50, 50, 50); //col times 50 is the x coordinate, and row times 50 is the y coordinate
}
}
}
}
Here is the code for how I check for collision in the same class:
public void collisionChecker(int playerX, int playerY){ //takes the user's location and then checks if they are running into the wall
if(mazeWalls[playerX / 50][playerY / 50] == 1 ){
setCollision(true);
}
else if(mazeWalls[playerX / 50][playerY / 50] != 1){
setCollision(false); //just in case
}
}
I feel like it should be working, but for some reason (I think it is something with the numbers after dividing the player's coordinates, or something) it is not.
Aucun commentaire:
Enregistrer un commentaire