2014-04-07 96 views
0

我做一个简单的2D游戏,的打砖块游戏项目。冲突检测2D

我正常工作,几乎所有的东西,但我被困在球与砖,即碰撞,在碰撞的时候,应该像一堵墙,扭转了球的方向。

,就会出现问题,以查看是否是否用砖块的碰撞是在侧碰撞水平或垂直时,例如,应在不改变Y轴只投资在X轴方向,反之亦然。

我没有得到发现,检查我的代码。

public void detectCollisionWithBricks() { 
    for (int i = 0; i < brickGroup.length; i++) { 
     for (int j = 0; j < brickGroup[i].length; j++) {     
      if (brickExists[i][j]) {      
       if (getEllipse().intersects(
         brickGroup.brick[i][j] 
           .getRectangle())) { 
        incY*=-1; 
        incX*=-1; 

        brickExists[i][j] = false; 
       } 
      } 
     } 
    } 
} 

代码:

-brickGroup: bidimensional array of bricks 

-brick: class painting a brick in the panel 

-brickExist: bidimensional array whit se same size as brickGroup, if false, doesn't paint the brick. 

-getEllipse(): returns an Ellipse2D.Double, with the coordinates of the ball. 

-getRectangle(): returns an Rectangle2D.Double, with the coordinates of the brick. 

-incX: increases the X position of the ball. 

-incY: increases the Y position of the ball. 

问,如果你不明白一些代码。

对不起,我的英语:(

在此先感谢

回答

0

你不能总是同时反转两个维度:

incY*=-1; 
incX*=-1; 

必须独立处理每个维度 尝试使用向量,看到这:2d collision response between circles

在你的情况下,它可能是简单的,它取决于EXI刺激incX或incY的价值。如果incX不为零且incY为零,则您正在水平移动。我建议不要使用1/-1,但一些变速和反转它:

incY = -incY; 
incX = -incX; 
0

我会推荐一种方法如下;

首先表示作为砖的2D阵列

bricks = new int[width][height]; 

在哪里可能根据需要可以改变网格的大小。通过这样做,你可以在给定时间检查根据球的位置的碰撞,意味着不会是一个耗时的检查循环

if (bricks[ballx/brickwidth][bally/brickheight] > 0) { 
    //we have a collision 
} 

接下来,您可以检查它是否是水平或垂直碰撞基于游戏的位置网格线的公差

if (bricks[ballx/brickwidth][bally/brickheight] > 0) { 
    if (ballx % gridwidth < tolerance) { 
     incx*=-1; 
    } 
    if (bally % gridheight < tolerance) { 
     incy*=-1; 
    } 
} 

这也应该处理冲突砖块

0

的边角如果您测量球和砖的中心之间的线的角度(易使用进行计算),你可以用它来确定球应该移动的方向。

而且,这将让你在浮点精度,而不仅仅是+1或改变方向-1。