2012-06-12 64 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爲小費 –