我有一个在屏幕上绘制位图的应用程序。我想避免重叠,但似乎我做错了什么。从图中可以看出,位图 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;
}