Android游戏开发---关于实体的绘制与跟踪技术
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 setterpublic 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~-1else if (px > x)//玩家的位置在右边dx = new Random().nextInt(3) + 1; //1~3else//正对着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);//保证子弹比飞机快, 设置敌机子弹的移动增量}}