先看看效果图:
分析:根据敌机类型区分 敌机 运动逻辑 以及绘制
/**
* 敌机
*
* @author liuml
* @time 2016-5-31 下午4:14:59
*/
public class Enemy {
// 敌机的种类标识
public int type;
// 苍蝇
public static final int TYPE_FLY = 1;
// 鸭子(从左往右运动)
public static final int TYPE_DUCKL = 2;
// 鸭子(从右往左运动)
public static final int TYPE_DUCKR = 3;
// 敌机图片资源
public Bitmap bmpEnemy;
// 敌机坐标
public int x, y;
// 敌机每帧的宽高
public int frameW, frameH;
// 敌机当前帧下标
private int frameIndex;
// 敌机的移动速度
private int speed;;
// 判断敌机是否已经出屏
public boolean isDead;
// 敌机的构造函数
public Enemy(Bitmap bmpEnemy, int enemyType, int x, int y) {
this.bmpEnemy = bmpEnemy;
frameW = bmpEnemy.getWidth() / 10;
frameH = bmpEnemy.getHeight();
this.type = enemyType;
this.x = x;
this.y = y;
// 不同种类的敌机血量不同
switch (type) {
// 苍蝇
case TYPE_FLY:
speed = 25;
break;
// 鸭子
case TYPE_DUCKL:
speed = 3;
break;
case TYPE_DUCKR:
speed = 3;
break;
}
}
// 敌机绘图函数
public void draw(Canvas canvas, Paint paint) {
canvas.save();
canvas.clipRect(x, y, x + frameW, y + frameH);
canvas.drawBitmap(bmpEnemy, x - frameIndex * frameW, y, paint);
canvas.restore();
}
// 敌机逻辑AI
public void logic() {
// 不断循环播放帧形成动画
frameIndex++;
if (frameIndex >= 10) {
frameIndex = 0;
}
// 不同种类的敌机拥有不同的AI逻辑
switch (type) {
case TYPE_FLY:
if (isDead == false) {
// 减速出现,加速返回
speed -= 1;
y += speed;
if (y <= -200) {
isDead = true;
}
}
break;
case TYPE_DUCKL:
if (isDead == false) {
// 斜右下角运动
x += speed / 2;
y += speed;
if (x > MySurfaceView.screenW) {
isDead = true;
}
}
break;
case TYPE_DUCKR:
if (isDead == false) {
// 斜左下角运动
x -= speed / 2;
y += speed;
if (x < -50) {
isDead = true;
}
}
break;
}
}
}
在MySurfaceView 中 生成敌机
public class MySurfaceView extends SurfaceView implements Callback, Runnable {
private SurfaceHolder sfh;
private Paint paint;
private Thread th;
private boolean flag;
private Canvas canvas;
// 1 定义游戏状态常量
public static final int GAME_MENU = 0;// 游戏菜单
public static final int GAMEING = 1;// 游戏中
public static final int GAME_WIN = 2;// 游戏胜利
public static final int GAME_LOST = 3;// 游戏失败
public static final int GAME_PAUSE = -1;// 游戏菜单
// 当前游戏状态(默认初始在游戏菜单界面)
public static int gameState = GAME_MENU;
// 声明一个Resources实例便于加载图片
private Resources res = this.getResources();
// 声明游戏需要用到的图片资源(图片声明)
private Bitmap bmpBackGround;// 游戏背景
private Bitmap bmpBoom;// 爆炸效果
private Bitmap bmpBoosBoom;// Boos爆炸效果
private Bitmap bmpButton;// 游戏开始按钮
private Bitmap bmpButtonPress;// 游戏开始按钮被点击
private Bitmap bmpEnemyDuck;// 怪物鸭子
private Bitmap bmpEnemyFly;// 怪物苍蝇
private Bitmap bmpEnemyBoos;// 怪物猪头Boos
private Bitmap bmpGameWin;// 游戏胜利背景
private Bitmap bmpGameLost;// 游戏失败背景
private Bitmap bmpPlayer;// 游戏主角飞机
private Bitmap bmpPlayerHp;// 主角飞机血量
private Bitmap bmpMenu;// 菜单背景
public static Bitmap bmpBullet;// 子弹
public static Bitmap bmpEnemyBullet;// 敌机子弹
public static Bitmap bmpBossBullet;// Boss子弹
public static int screenW;
public static int screenH;
// 声明一个敌机容