【发布时间】:2014-04-03 02:15:11
【问题描述】:
我正在尝试在 Eclipse 的 SDK 中为 Android 的学校项目制作弹球式游戏。
有一个非常奇怪且非常令人沮丧的问题,即对象在没有任何代码告诉它们移动的情况下移动。基本上,每个 Wall 实例包含 4 个 Line 对象,用于与 Ball 进行碰撞检测。这些线条第一次起作用,但是一旦球与它们碰撞一次,那条线条就会以某种方式移动到屏幕上的另一个位置。 我一直在调试它,并且不会问我是否还没有尝试过所有的东西,但老实说,没有理由让 Line 转移到任何地方。我处理碰撞的方法是将球推离墙壁 1px,然后给定新的 dx 和 dy(速度)以使其离开。下面是检查碰撞的代码,后面是处理碰撞以改变球的位置和速度的函数。两者都是 Ball 类中的方法。
GameElement[] walls = currLevel.getWalls();
int i, j;
Line[] lines;
Line line;
RectF lineBounds;
boolean hadCollision = false;
for (i = 0; i < walls.length & !hadCollision; i++) {
lines = walls[i].getLines();
for (j = 0; j < lines.length & !hadCollision; j++) {
lineBounds = lines[j].getBounds();
if (lineBounds.intersect(point)) {
paint.setColor(Color.BLUE); // Colour ball blue.
reactToCollision3(lines[j]);
// TEST RESET!!!
//this.x = (float)(648+40);
//this.y = (float)(900-30);
hadCollision = true;
//printWallsLines();
}
}
}
处理碰撞的函数是:
public void reactToCollision3 (Line line) {
float liney = line.sy;
float linex = line.sx;
if (line.rotation == 0.0) { // HORIZONTAL EDGE
if (this.y > liney) { // Ball moving upward hits the bottom of a wall.
this.y = liney + this.radius + 1.0f;
} else { // Ball moving downward hits the top of a wall.
this.y = liney - this.radius - 1.0f;
}
this.dy *= -1.0f;
} else { // VERTICAL EDGE
if (this.x > linex) { // Ball moving leftward hits right edge of a wall.
this.x = linex + this.radius + 1.0f;
} else { // Ball moving rightward hits left edge of a wall.
this.x = linex - this.radius - 1.0f;
}
this.dx *= -1.0f;
}
所以当我现在运行这个时,球在第一次击中它时会从墙上反弹,然后它击中的那条线(墙的边缘)会转移到其他地方,但由于墙是不可见的被绘制为一个单元,因此组成它的线条不会影响绘图。 如果我注释掉“this.x = ...”和“this.y = ...”的行,那么这个问题就不会再发生了。此外,如果我在上述函数中取消注释用于设置球位置的测试 RESET 行,那么该行也不会移动。但是一旦我运行它,它就会再次发生。
我快疯了,想知道为什么会这样。请给我建议。 谢谢!
【问题讨论】:
标签: java android collision-detection game-physics