round checks ideas: two from the center of the circle is smaller than the radius of the two circles and then collide , and vice versa , no collisions
/**
* 两个圆的碰撞检测
* @param x1
* @param y1
* @param r1
* @param x2
* @param y2
* @param r2
* @return
*/
public static boolean CheckCollideCircle(int x1, int y1, int r1, int x2,
int y2, int r2) {
boolean iscollide=false;
//两点之间的距离 小于两半径之和就发生了碰撞
if(Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2, 2))<=r1+r2){
iscollide=true;
}
return iscollide;
}
Liezi below with a full description
public class CircleSurfaceView extends SurfaceView implements Callback,Runnable {
int x1=70,y1=110,r1=40;
int x2=220,y2=110,r2=40;
boolean isCollide=false;//是否发生碰撞
SurfaceHolder surfaceHolder;
Paint paint;
boolean flag=false;
int sleeptime=100;
Thread thread;
public CircleSurfaceView(Context context) {
super(context);
surfaceHolder=getHolder();
surfaceHolder.addCallback(this);
paint=new Paint();
paint.setTextSize(12);
thread=new Thread(this);
flag=true;
}
public void draw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
if(isCollide){
paint.setColor(Color.RED);
canvas.drawText("Collide", 0, 30, paint);
}
else {
paint.setColor(Color.WHITE);
canvas.drawText("Not Collide", 0, 30, paint);
}
canvas.drawCircle(x1, y1, r1, paint);
canvas.drawCircle(x2, y2, r2,paint);
}
/**
* 触屏点击事件
*/
@Override
public boolean onTouchEvent(MotionEvent event){
x1=(int)event.getX()-r1/2; //圆心坐标
if(CheckCollide.CheckCollideCircle(x1, y1, r1, x2, y2, r2)){//检查碰撞的方法
isCollide=true;
}
else {
isCollide=false;
}
return true;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
if(!thread.isAlive()){
thread.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
flag=false;
thread=null;
}
@SuppressLint("WrongCall")
@Override
public void run() {
// TODO Auto-generated method stub
Canvas canvas=null;
while (flag) {
try {
canvas=surfaceHolder.lockCanvas();
synchronized (canvas) {
draw(canvas);
}
} catch (Exception e) {
Log.e("Collide", e.getMessage());
}finally{
if(canvas!=null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
try {
Thread.sleep(sleeptime);
} catch (Exception e) {
Log.e("Collide", e.getMessage());
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
}
没有评论:
发表评论