Android 小球碰撞检测技术

Android 小球碰撞检测技术_第1张图片


核心代码 

public class BallThread extends Thread {
boolean flag;
Ball ball;
double currentTime;


public BallThread(Ball ball) {
flag = true;
this.ball = ball;
}


@Override
public void run() {
while (flag) {
// 调试:碰撞检测开始的时间
// long stime = System.currentTimeMillis();

currentTime = System.nanoTime();
double timeSpanX = (currentTime - ball.startTimeX) / 1000 / 1000 / 1000;
double timeSpanY = (currentTime - ball.startTimeY) / 1000 / 1000 / 1000;
int xBackup = ball.x;
int yBackup = ball.y;
ball.x = (int) (ball.startX + ball.vX * timeSpanX);
ball.y = (int) (ball.startY + ball.vY * timeSpanY);


// 检测是否撞到边界
if ((ball.vX > 0 && (ball.x + ball.r) > Comment.W)
|| (ball.vX < 0 && (ball.x - ball.r) < 0)) {
ball.x = xBackup;
ball.vX = 0 - ball.vX;// 速度反向
ball.startTimeX = System.nanoTime();
ball.startX = ball.x;
}
if ((ball.vY > 0 && (ball.y + ball.r) > Comment.H)
|| (ball.vY < 0 && (ball.y - ball.r) < 0)) {
ball.y = yBackup;
ball.vY = 0 - ball.vY;
ball.startTimeY = System.nanoTime();
ball.startY = ball.y;
}


// 检测是否撞到障碍物
for (int i = 0; i < GameView.alObstacle.size(); i++) {
Obstacle o = GameView.alObstacle.get(i);
if (Math.abs(ball.x - o.x) < (ball.r + o.hWidth)
&& Math.abs(ball.y - o.y) < (ball.r + o.hWidth)) {
if (Math.abs(xBackup - o.x) >= (ball.r + o.hWidth)) {
ball.x = xBackup;
ball.vX = 0 - ball.vX;// 速度反向
ball.startTimeX = System.nanoTime();
ball.startX = ball.x;
}
if (Math.abs(yBackup - o.y) >= (ball.r + o.hWidth)) {
ball.y = yBackup;
ball.vY = 0 - ball.vY;
ball.startTimeY = System.nanoTime();
ball.startY = ball.y;
}
break;
}
}

// 调试:碰撞检测结束的时间
// long etime = System.currentTimeMillis();
// System.out.println(etime + " - " + stime + " = " + (etime - stime));// 现实证明:碰撞检测基本不消耗时间


try {
Thread.sleep(5);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


csdn demo下载地址:http://download.csdn.net/detail/qq_28934205/9366278


你可能感兴趣的:(android,碰撞技术)