画面にビットマップを描画するアプリケーションがあります。重複を避けたいのですが、何か間違っているようです。図からわかるように、ビットマップ 52 と 53 が重なっています。
ID:52 X START:974.0 X FINISH:1166.0 Y START:1044.0 Y END:1236.0 ID
:53 X START:833.0 X FINISH:1025.0 Y START:898.0 Y END:1090.0
衝突が発生するかどうか、または何が発生するかを調べてみました。結果は次のとおりです。半径 = (1166 - 974)/2 = 95
dx = (974 + 96) - (833 + 96) = 1070 - 929 = 141
dy = (1044 + 96) + (898 + 96) = 1140 - 994 = 146
距離= 141*141 + 146*146 = 19881 + 21316 = 41197
ブール値 = 41197 < (96 +96) * (96+96) ? ----- 41197 < 36864 ?
いいえ、衝突しません。重なり合っていません...
画面で重なり合っているのはなぜですか?
//this function makes sure that balls are not overlapping themselves
public void setBalls() {
for (int bubu=0;bubu <12;bubu++) {// creates 12 blue balls
ball = new Ball(BitmapFactory.decodeResource(getResources(),R.drawable.circle));
boolean ok = false;
while (!ok) {
ball.realx = (random.nextInt(canvasWidth) - ball.getRadius());
ball.realy = (random.nextInt(canvasHeight) - ball.getRadius());
Log.d("ball","ID:"+ball.id+" X START:"+ball.realx+ " X FINISH:"+ (ball.realx + (ball.getRadius())*2) + " Y START:"+ball.realy+" Y END:"+(ball.realy+ (ball.getRadius())*2));
ok = canStartHere(ball);
}
ballContainer.add(ball);
}
}
//helper function of setBalls()
public boolean canStartHere(Ball ball) {
boolean conditionClear = true;
for (Ball balll: ballContainer) {
if (hitTest(ball, balll)){
conditionClear = false;
}
}
return conditionClear;
}
// return whether ball intersects ball2 or not
public boolean hitTest(Ball ball, Ball ball2) {
boolean hit = false;
float dx = (ball.realx + ball.radius) - (ball2.realx + ball2.radius);
float dy = (ball.realy + ball.radius) - (ball2.realy + ball2.radius);
float dist = (dx * dx) + (dy * dy);
if (dist <= (ball.getRadius() + ball2.getRadius()) * (ball.getRadius() + ball2.getRadius())) {
// THERE IS AN INTERSECTION
hit = true;
} else {
// no intersection
}
return hit;
}
そして、これがBallクラスです
public class Ball {
Bitmap bitmap;
int radius, speed, angle, mass,id;
float posx, posy,realx,realy;
double velX;
double velY;
static int totalID = 0;
Random random = new Random();
public Ball(Bitmap image) {
this.bitmap = image;
this.id = totalID;
totalID ++;
double tempAngle = random.nextInt(361);
double tempRadians = tempAngle * (Math.PI/180);
//velX = Math.cos(tempRadians)*4; commented out so they are still
//velY = Math.sin(tempRadians)*4;
Log.d("tag", "created a ball with ID " + this.id);
this.radius = (bitmap.getWidth() / 2);
this.mass = radius;
}
public int getRadius() {
return radius;
}