当前位置:网站首页 > 游戏 >

android 游戏 碰撞检测

来源:www.999sf.com | 编辑:999搜服 | 发布时间:2016-05-31 00:03

小编导读:

矩形碰撞 原理: 两个矩形位置 的四种情况 不是这四中情况 则碰撞圆形碰撞 原理: 利用两个圆心之间的距离进行判定.当两个圆心的距离小于半径之和则碰撞.像素碰撞

像素碰撞 :不适用 遍历所有像素 检测 太多了

矩形碰撞 代码:

public class MySurfaceView extends SurfaceView implements Callback, Runnable { private SurfaceHolder sfh; private Paint paint; private Thread th; private boolean flag; private Canvas canvas; private int screenW, screenH; //定义两个矩形的宽高坐标 private int x1 = 10, y1 = 110, w1 = 40, h1 = 40; private int x2 = 100, y2 = 110, w2 = 40, h2 = 40; //便于观察是否发生了碰撞设置一个标识位 private boolean isCollsion; /** * SurfaceView初始化函数 */ public MySurfaceView(Context context) { super(context); sfh = this.getHolder(); sfh.addCallback(this); paint = new Paint(); paint.setColor(Color.WHITE); paint.setAntiAlias(true); setFocusable(true); } /** * SurfaceView视图创建,响应此函数 */ @Override public void surfaceCreated(SurfaceHolder holder) { screenW = this.getWidth(); screenH = this.getHeight(); flag = true; //实例线程 th = new Thread(this); //启动线程 th.start(); } /** * 游戏绘图 */ public void myDraw() { try { canvas = sfh.lockCanvas(); if (canvas != null) { canvas.drawColor(Color.BLACK); if (isCollsion) { paint.setColor(Color.RED); paint.setTextSize(20); canvas.drawText("Collision!", 0, 30, paint); } else { paint.setColor(Color.WHITE); } //绘制两个矩形 canvas.drawRect(x1, y1, x1 + w1, y1 + h1, paint); canvas.drawRect(x2, y2, x2 + w2, y2 + h2, paint); } } catch (Exception e) { // TODO: handle exception } finally { if (canvas != null) sfh.unlockCanvasAndPost(canvas); } } /** * 触屏事件监听 */ @Override public boolean onTouchEvent(MotionEvent event) { //让矩形1随着触屏位置移动 x1 = (int) event.getX() - w1 / 2; y1 = (int) event.getY() - h1 / 2; if (isCollsionWithRect(x1, y1, w1, h1, x2, y2, w2, h2)) { isCollsion = true; } else { isCollsion = false; } return true; } /** * 按键事件监听 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } /** * 游戏逻辑 */ private void logic() { } public boolean isCollsionWithRect(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) { if (x1 >= x2 && x1 >= x2 + w2) { return false; } else if (x1 <= x2 && x1 + w1 <= x2) { return false; } else if (y1 >= y2 && y1 >= y2 + h2) { return false; } else if (y1 <= y2 && y1 + h1 <= y2) { return false; } return true; } @Override public void run() { while (flag) { long start = System.currentTimeMillis(); myDraw(); logic(); long end = System.currentTimeMillis(); try { if (end - start < 50) { Thread.sleep(50 - (end - start)); } } catch (InterruptedException e) { e.printStackTrace(); } } } /** * SurfaceView视图状态发生改变,响应此函数 */ @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * SurfaceView视图消亡时,响应此函数 */ @Override public void surfaceDestroyed(SurfaceHolder holder) { flag = false; } }
文章-android 游戏 碰撞检测,是由http://999sf.com提供,转载请注明版权出处!

上一篇:在两名来派出所报案女子的带领下

下一篇:但我的任务是接待好各位贵宾