2016-12-26 35 views
0

我新的android。試圖實現彼此的彈跳球。像thisAndroid Canvas.How要計算循環中心之間的差異?

我BouncingBallView類的樣子:

private ArrayList<Ball> balls; 

public BouncingBallView(Context context) { 
    super(context); 
    this.balls = new ArrayList<>(); 


    for(int i=0; i<2; i++) 
     this.balls.add(addBall()); 
} 

public Ball addBall(){ 

    Ball ball; 

    // Init the ball at a random location (inside the box) and moveAngle 
    Random rand = new Random(); 
    int radius = 60; 
    int x = rand.nextInt(500 - radius * 2 - 20) + radius + 10; 
    int y = rand.nextInt(800- radius * 2 - 20) + radius + 10; 
    int speed = 10; 
    int angleInDegree = rand.nextInt(360); 

    ball = new Ball(x, y, radius, speed, angleInDegree); 

    return ball; 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 

    for(int i=0; i < balls.size(); i++) 
     balls.get(i).draw(canvas); 

    for(int i=0; i < balls.size(); i++){ 

     balls.get(i).intersect(canvas); 
     // Update the ball's state with proper collision response if collided. 
     balls.get(i).update(); 
    } 

    for(int i=0; i<balls.size(); i++){ 
     balls.get(i).collide(balls); 

    } 


    invalidate(); 
} 

和類球有衝撞的方法();

public void collide(ArrayList<Ball> balls){ 
    //Log.d("TEst", "LOG"); 

    // Calculate difference between centres 
    float distX = balls.get(0).getBallX() - balls.get(1).getBallX(); 
    float distY = balls.get(0).getBallY() - balls.get(1).getBallY(); 

    // Get distance with Pythagora 
    double dist = Math.sqrt((distX * distX) + (distY * distY)); 

    float r = ballRadius + ballRadius; 
    if ((float) dist <= r) { 
     Log.d("Collide", "Detected"); 
     this.ballSpeedX = -this.ballSpeedX; 
     this.ballSpeedY = -this.ballSpeedY++; 
    } 
    /*for(int i=0; i < balls.size(); i++) { 

     for(int j=1; j<balls.size(); j++) { 
      // Calculate difference between centres 
      float distX = balls.get(i).getBallX() - balls.get(j).getBallX(); 
      float distY = balls.get(i).getBallY() - balls.get(j).getBallY(); 

      // Get distance with Pythagora 
      double dist = Math.sqrt((distX * distX) + (distY * distY)); 

    *//*double distance = Math.sqrt(((balls.get(0).getBallX() - balls.get(1).getBallX()) * (balls.get(0).getBallX() - balls.get(1).getBallX())) + ((balls.get(0).getBallY() 
       - balls.get(1).getBallY()) * (balls.get(0).getBallY() - balls.get(1).getBallY())));*//* 

      float r = ballRadius + ballRadius; 
      if ((float) dist <= r) { 
       Log.d("Collide", "Detected"); 
       this.ballSpeedX = -this.ballSpeedX; 
       this.ballSpeedY = -this.ballSpeedY++; 
      } 
     } 
    }*/ 

} 

在這裏,我使用的畢達哥拉斯定理,一個^ 2 + B^2 = C^2,找出兩個圓之間的距離中心。如何計算球數是否> 2.我嘗試循環,但效果很差(冰球)。

的完整代碼,你可以找到github

現在想在這個視頻my bouncing ball video

THX的工作有所幫助;)

P.S對不起這麼糟糕的英語。

回答

0

你可以在每個階段有一個球的計數器,當一個球被摧毀時(如果你摧毀它們),你可以改變計數,你可以在碰撞方法中檢查(計數器)。

但我不是你需要檢查這種情況,如果碰撞發生然後確定否則什麼都不應該發生這種方法。