2012-06-12 65 views
0

我已经绘制了不同大小和位置的多个圆圈到一个画布,但我需要检测它们之间的碰撞。Android:如何检测两个圆圈之间的碰撞

public void run() {   
      while(Run){ 
       if(!sHold.getSurface().isValid()) 
        continue; 

       c[0][cnum].r++; 
       canvas = sHold.lockCanvas(); 
       canvas.drawRGB(02, 02, 150); 
       Paint white = new Paint(); 
       white.setColor(Color.WHITE); 
       if(c[0][cnum].x != 0 && c[0][cnum].y != 0) 
        canvas.drawCircle(c[0][cnum].x, c[0][cnum].y, c[0][cnum].r, white); 
       if(cnum!=0) 
        for(int i=0; i<cnum; i++) 
         canvas.drawCircle(c[1][i].x, c[1][i].y, c[1][i].r, white); 
       sHold.unlockCanvasAndPost(canvas); 
       if(((c[0][cnum].x - c[0][cnum].r)<0)||((c[0][cnum].y-c[0][cnum].r)<0)||((c[0][cnum].y+c[0][cnum].r)>height)||((c[0][cnum].x+c[0][cnum].r>width))){ 
        c[1][cnum].x = c[0][cnum].x; 
        c[1][cnum].y = c[0][cnum].y; 
        c[1][cnum].r = c[0][cnum].r; 
        broken = true; 
        break; 
       } 
      } 
     } 

回答

4

你不应该在渲染阶段这样做。

当处理逻辑你应该检查是否界相交如所描述的:

V1 = CIRCLE2

相交= V1的CIRCLE1 V2 =中心的中心 - V2 < circle1radius + circle2radius

0

这链接非常有用!

Circle-Circle Collisions

这是非常详细和didatic


在该页面的底部有另一个链接,以更详细的东西!


我用中心方法之间的距离--- Circles

通过测量每个中心可以,如果他们说的碰撞之间的距离。 距离不应超过2半径的总和。

这里就是我所做的:

private boolean checkDrawContains(ShapeDrawable newHole) 
{ 
    long newCenterX = newHole.getBounds().left + (newHole.getBounds().width()/2); //Get the center of my shapes 
    long newCenterY = newHole.getBounds().top + (newHole.getBounds().height()/2); 

    for(ShapeDrawable hole: mHoles) // I was storing the circles in an ArrayList 
    { 
     long centerX = hole.getBounds().left + (hole.getBounds().width()/2); //Get the center of my shapes 
     long centerY = hole.getBounds().top + (hole.getBounds().height()/2); 
     long x = centerX - newCenterX; 
     long y = centerY - newCenterY; 
     long aux = (long) ((Math.pow(Math.abs(x),2)) + (Math.pow(Math.abs(y),2))); //Pythagoras the hard way :P 
     long distance = (long) Math.sqrt(aux); 
     long sRads = (newHole.getBounds().width()/2) + (hole.getBounds().width()/2); 

     if(distance <= sRads) { 
      return true; //Is Colliding! 
     } 
    } 
    return false; // Is not Colliding! 
} 
+0

你能进一步解释一下,答案是,你通过阅读该链接发现了什么?我们希望尝试在帖子中提供所有可用的信息来回答问题,使其对未来的帖子的读者更有用。 – McWayWeb

+0

刚刚做到了! Thx为小费 –