Android游戏开发中,特别是飞行射击类游戏经常出现子弹的跟踪功能。贴一段代码。
public class Enemy { private int x, y; private Bitmap ePlayer; private boolean flag = true;//标记是否有效. 被击中后变为无效的. private int dx, dy; //飞机的偏移量 private int pWidth, pHeight; private GameView gameView; private EnemyBullet enemyBullet; //getter and setter public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public Enemy(View view) { gameView = (GameView) view; pWidth = view.getWidth(); pHeight = view.getHeight(); x = new Random().nextInt(pWidth); //敌机出现的位置0-320(屏幕宽度) y = new Random().nextInt(50) - 50; //上移50像素, 有高有低的慢慢出来 dy = new Random().nextInt(10) + 1;//1-10, 至少得动吧 ePlayer = BitmapFactory.decodeResource(view.getResources(), R.drawable.e6); } public void drawSelf(Canvas canvas) { if (flag) //敌机管理里面已经检测了 canvas.drawBitmap(ePlayer, x, y, null); } public void enemyCheckCrash() { //遍历所有子弹 for (PlayerBullet playerBullet : PlayerBulletManager .getAllPlayerBullet()) { //如果敌机和玩家子弹都是有效的, 且发生碰撞 if (this.flag == true && playerBullet.isFlag() == true && CheckCrash .ifCrash( x, y, x + ePlayer.getWidth(), y + ePlayer.getHeight(), playerBullet.getX(), playerBullet.getY(), playerBullet.getX() + playerBullet.getBulletWidth(), playerBullet.getY() + playerBullet.getBulletHeight())) ; { //打到后敌机消失, 玩家子弹消失 this.flag = false; playerBullet.setFlag(false); System.out .println(x + " " + y + " " + (x + ePlayer.getWidth()) + " " + (y + ePlayer.getHeight()) + " " + playerBullet.getX() + " " + playerBullet.getY() + " " + (playerBullet.getX() + playerBullet .getBulletWidth()) + " " + (playerBullet.getY() + playerBullet .getBulletHeight())); } } } /** * 敌机移动是随机的. 包括出现也是随机的. */ public void move() { //将偏移量的设置放到这里, 让飞机每次生成时的偏移的变化的 int px = gameView.getPlayerManager().getPlayer().getX(); //跟踪功能, 即设置dx增量 if (px < x) //玩家的位置在左边 dx = new Random().nextInt(3) - 3;//-3~-1 else if (px > x)//玩家的位置在右边 dx = new Random().nextInt(3) + 1; //1~3 else //正对着 dx = 0; //敌机慢慢移动 x += dx; y += dy; //敌机出屏幕后, 再重新回到上面去. 敌机中子弹了也要回到上面去 if (x < -1 * ePlayer.getWidth() || x > pWidth || y > pHeight) //|| this.flag == false) { x = new Random().nextInt(pWidth);//敌机出现的位置0-320(屏幕宽度) y = new Random().nextInt(50) - 50; //上移50像素, 有高有低的慢慢出来 //this.flag = true; //飞机又重新有效 } } /** * 敌机发射子弹 */ public void fire() { enemyBullet = gameView.getEnemyBulletManager().getOneBullet(); //设置子弹的位置. //x = 敌机当前x + 敌机宽度/2 - 子弹宽度/2 //y = 敌机当前y + 飞机高度 (子弹高度 这里就不计算了) enemyBullet.setPosition( x + ePlayer.getWidth() / 2 - enemyBullet.getEnemyBulletWidth() / 2, y + ePlayer.getHeight()); enemyBullet.setDy(dy + 3);//保证子弹比飞机快, 设置敌机子弹的移动增量 } }