Bullets are essential in aircraft games. They are numerous and full of the whole screen. These random or small objects with a certain amount of AI are not always easy to implement, sometimes you have to consider many performance-related issues. We have previously defined a GameObject to facilitate the reuse of Sprite. because we have a lot of bullets, it is impossible to share the same Sprite without adding one bullet. We implement this by inheriting GameObject.
The following describes the bullet categories:
It will inherit from GameObject;
Record the number of bullets;
A bullet status Array records the type, position x, y, speed vx, vy, and alive of each bullet.
Initialize bullets
Draw a bullet to the screen.
A collision detection method.
Well, let's take a look. The following is the definition of the bullet class. Pay attention to this idea-reuse Sprite, which is very important. (Many designs of tony are referenced here)
Public class Bullets extends GameObject {
Private int [] [] bullets; // array of bullet states
Private int bulletstotal; // The length of the array
Private Random rnd; // Random Number
Public static final int BULLET_TYPE_LEFT = 0; // Position Type of the bullet Initialization
Public static final int BULLET_TYPE_RIGHT = 1; // It can be divided into four types: upper, lower, and left.
Public static final int BULLET_TYPE_TOP = 2;
Public static final int BULLET_TYPE_BOTTOM = 3;
Private int width, height; // the height and width of the screen, used for random bullet positions
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 () {// array of initial bullet status
For (int I = 0; I <bullets. length; I ++ ){
InitBullet (I );
}
}
Private void initBullet (int I) {// initialize the index bullet
Bullets [I] [0] = (rnd. nextInt () & 0x7fffffff) % 4; // type
Bullets [I] [5] = 1; // alive 1 indicates survival, 0 indicates death
Switch (bullets [I] [0]) {
Case BULLET_TYPE_LEFT:
Bullets [I] [1] =-5;
Bullets [I] [2] = (rnd. nextInt () & 0x7fffffff) % height;