一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

J2ME 2D小游戏入门之旅(四) 加入子弹群,实现碰撞运算

时间:2008-01-12 编辑:简简单单 来源:一聚教程网

飞机类游戏中子弹是必不可少的,他们数量很多且充斥着整个屏幕,这些随机或者有着一定AI的小物体,实现起来不是总那么容易,有时候你不得不考虑很多和效能有关的问题。我们之前定义了GameObject,很大程度上就是为了方便的重用Sprite,因为我们有很多的子弹,不可能没增加一个子弹都是一个Sprite,我需要共享同一个Sprite。我们通过继承GameObject来实现。
下面分析一下这个子弹类:
它将继承自GameObject;
记录子弹的个数;
一个子弹的状态数组,记录各个子弹的类型type,位置x,y,速度vx,vy,是否存活alive等等。
初始化子弹
一个绘制方法,将子弹画到屏幕上。
一个碰撞检测方法。
好了先这样吧,以下是我们子弹类的定义,注意这种思想――重用Sprite,这很重要。(这里参考了tony的很多设计)
public class Bullets extends GameObject {
private int[][] bullets;//子弹状态数组
private int bulletstotal;//数组的length
private Random rnd;//随机数
public static final int BULLET_TYPE_LEFT=0;//子弹初始化的位置类型
public static final int BULLET_TYPE_RIGHT=1;//分为上下左右四种
public static final int BULLET_TYPE_TOP=2;
public static final int BULLET_TYPE_BOTTOM=3;
private int width,height;//屏幕的高和宽,用于随机子弹位置
public Bullets(Image img,int picwidth,int picheight,int bulletstotal,int width,int height) {
super(img,picwidth,picheight);
this.bulletstotal=bulletstotal;
bullets=new int[bulletstotal][6];
rnd=new Random();
this.width=width;
this.height=height;
}
public void initBullets(){//初始化子弹状态数组
for (int i = 0; i < bullets.length; i++) {
initBullet(i);
}
}
private void initBullet(int i) {//初始化index号子弹
bullets[i][0] = (rnd.nextInt() & 0x7fffffff) % 4; //type
bullets[i][5] = 1; //alive 1表示存活, 0表示死去
switch (bullets[i][0]) {
case BULLET_TYPE_LEFT:
bullets[i][1] = -5;
bullets[i][2] = (rnd.nextInt() & 0x7fffffff) % height;

热门栏目