2015-05-08 26 views
1

因此,目前我正在制作迷宫游戏,当然,它是一个迷宫游戏,它必须有墙壁。墙壁需要阻止玩家越过他们。我在检查碰撞时遇到问题。它在一些地方有效,而其他地方则不适用。我目前的方法是通过我的二维数组,通过将他们当前的x和y除以50,然后使用这两个数字来尝试查看玩家是否会碰撞墙或不。正在发生的事情是,它阻止了玩家移动到某些墙上,有些则没有。此外,它还会阻止玩家在没有墙的地方(值为2的值)。我觉得有些东西正在与数学混淆,但我无法弄清楚什么。下面是我如何制作迷宫,伴随着阵列它正在从制造代码:试图通过2d数组,并没有得到正确的值?

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 
      } 
     } 
    } 
} 

这里是我如何在同一个班级检查碰撞的代码:

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 
    } 
} 

我觉得它应该起作用,但由于某种原因(我认为这是用分割玩家坐标之后的数字来表示),但事实并非如此。

+0

我相信'playerX'和'playerY'是用户点击的坐标,然后你试图获得该rectanagle左上角的cooridnates来确定是否碰撞。对? –

+0

playerX和playerY的实际值是多少,它们总是可以被50整除?如果不是,那可能是问题。 – Chizzle

回答

1

在2D阵列的第一索引是按照惯例行索引,第二个是列索引,所以你的坐标是错误的方式轮:

public void collisionChecker(int playerX, int playerY){ //takes the user's location and then checks if they are running into the wall 
    if(mazeWalls[playerY/50][playerX/50] == 1){ 
     setCollision(true); 
    } 
    else if(mazeWalls[playerY/50][playerX/50] != 1){ 
     setCollision(false); //just in case 
    } 
} 

此代码可以简化为

public void collisionChecker(int playerX, int playerY){ //takes the user's location and then checks if they are running into the wall 
    setCollision(mazeWalls[playerY/50][playerX/50] == 1); 
} 
+0

我原本以为这样做,但我决定它不会做任何事情(显然我错了,不知道为什么我不试试这个)。我仍然可以穿过一些围墙,但就目前而言,这似乎几乎无法避免。如果你有任何想法,为什么这样做让我知道,但你的解决方案确实解决了它。 – user1234

+0

如果玩家仍然遇到问题,请考虑玩家的宽度和高度,而不是只测试一个点(playerX,playerY)。假设玩家X,玩家Y(玩家X,玩家Y,玩家Y)和玩家X +玩家宽度,玩家Y +玩家高度),只要玩家小于一平方的大小,你应该能够测试(玩家X +玩家宽度,玩家Y)是你的玩家精灵的左上角 – samgak

+0

好吧,我会确保尝试一下。 – user1234