添加爆炸效果
1.在game包里创建Explode类。
package game;
import java.awt.*;
public class Explode {
public static final int EXPLODE_FRAME_COUNT = 12;
private static Image[] img;
static {
img = new Image[EXPLODE_FRAME_COUNT/4];
for (int i = 0; i < img.length; i++) {
img[i] = Toolkit.getDefaultToolkit().createImage("res/boom_" + i + ".png");
}
}
//爆炸的效果的坐标
private int x, y;
//当前播放的帧的下标0-11
private int index;
//是否可见
private boolean visible=true;
public Explode(int x,int y) {
this.x = x;
this.y = y;
}
public void draw(Graphics g) {
if(!visible)return ;
g.drawImage(img[index/4], x, y, null);
index++;
//播放完最后一帧,设置不可见
if(index>=EXPLODE_FRAME_COUNT)
visible=false;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
2.在Tank类调用
坦克可能会同时被多个坦克击中,产生爆炸效果,所以创建容器来存储。
private List<Explode> explodes =new ArrayList();
//坦克和子弹碰撞的方法
public void collideBullets(List<Bullet> bullets)
{
for (Bullet bullet:bullets)
{
int bulletX = bullet.getX();
int bulletY = bullet.getY();
if(MyUtil.isCollide(x,y,RADIUS,bullet.getX(),bullet.getY()))
{
//子弹消失
bullet.setVisible(false);
//坦克受到伤害
//添加爆炸效果
explodes.add(new Explode(bulletX,bulletY));
}
}
}
绘制当前坦克上的爆炸效果。
/**
* 绘制当前坦克上的爆炸效果
* @param g
*/
public void drawExplodes(Graphics g)
{
for(Explode explode : explodes){
explode.draw(g);
}
}
3.在GameFrame被调用
//所有的坦克上的爆炸效果
private void drawExplode(Graphics g){
for(Tank enemy :enemies){
enemy.drawExplodes(g);
}
myTank.drawExplodes(g);
}
private void drawRun(Graphics g) {
g.setFont(GAME_FONT);
//绘制黑色的背景
g.setColor(Color.black);
g.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
drawEnemies(g);
myTank.draw(g);
bulletCollideTank();
drawExplode(g);
}