android游戏开发学习笔之九 (学习书籍 Android游戏编程之从零开始)

/**
* 矩形碰撞
*
* @time 上午11:29:26
* @author retacn yue
* @Email [email protected]
*/
@SuppressWarnings("unused")
public class RectCollisionSurfaceView extends SurfaceView implements Callback, Runnable {
private int screenX, screenY;
private SurfaceHolder sfh;
private Thread thread;
private Canvas canvas;
private boolean flag;
private Paint paint;


// 两个矩形的宽高/坐标
private int x1 = 10, y1 = 100, w1 = 50, h1 = 50;
private int x2 = 100, y2 = 100, w2 = 50, h2 = 50;


// 是否发生碰撞
private boolean isCollision;


public RectCollisionSurfaceView(Context context) {
super(context);
sfh = this.getHolder();
sfh.addCallback(this);


paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);


this.setFocusable(true);


}


@Override
public void surfaceCreated(SurfaceHolder holder) {
screenX = this.getWidth();
screenY = this.getHeight();


flag = true;
thread = new Thread(this);
thread.start();


}


@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {


}


@Override
public void surfaceDestroyed(SurfaceHolder holder) {
flag = false;
}


@SuppressWarnings("static-access")
@Override
public void run() {
while (flag) {
try {
long start = System.currentTimeMillis();
// 绘图
draw();
// 游戏逻辑
logic();
long end = System.currentTimeMillis();
if (end - start < 50) {
thread.sleep(50 - (end - start));


}
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}


/**
* 绘制图形
*/
private void draw() {
try {
canvas = sfh.lockCanvas();
if (null != canvas) {
canvas.drawColor(Color.BLACK);


if (isCollision) {
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, y2 + w2, y2 + h2, paint);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != canvas) {
sfh.unlockCanvasAndPost(canvas);
}
}


}


/**
* 游戏逻辑
*/
private void logic() {


}


/**
* 检察是否发 生碰撞
*
* @param h2
* @param w2
* 矩形一的四个坐标
* @param y2
* @param x2
*
* @param h1
* @param w1
* 矩形二的四个坐标
* @param y1
* @param x1
*/
private boolean isCollidionRect(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {
/************ 分四种情况 **************/
// 图片一位于图片二的上方
if (y1 <= y2 && y1 + h1 < y2) {
return false;
}
// 位于下方
if (y2 <= y1 && y2 + h2 < y1) {
return false;
}
// 位于左边
if (x1 <= x2 && x1 + w1 < x2) {
return false;
}
// 位于右边
if (x1 >= x2 && x1 >= x2 + w2) {
return false;
}
return true;
}


/********************** 事件临听 *************************/


@Override
public boolean onTouchEvent(MotionEvent event) {
// 图片1随鼠标移动 (根据触摸到的焦点来取得图片的位置)
x1 = (int) event.getX() - w1 / 2;
y1 = (int) event.getY() - h1 / 2;


// 检察是否发生碰撞()
if (isCollidionRect(x1, y1, w1, h1, x2, y2, w2, h2)) {
isCollision = true;
} else {
isCollision = false;
}


return super.onTouchEvent(event);
}


/*********************************************************/
}

你可能感兴趣的:(android)