爆照的效果是一张张图片。
将爆炸的图片加载到内存中:
public static BufferedImage[] explodes = new BufferedImage[16];
for(int i=1;i<=16;i++){
explodes[i] = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream(“images/e”+i+".gif"));
}
定义一个爆炸类:(万物皆对象)
package com.tavon.tank;
import java.awt.*;
public class explode {
public static final int WIDTH = ResourceMgr.explodes[0].getWidth();
public static final int HEIGHT = ResourceMgr.explodes[0].getHeight();
private int x, y;
private TankFrame tankFrame = null;
public explode(int x, int y, TankFrame tankFrame) {
this.x = x;
this.y = y;
this.tankFrame = tankFrame;
}
private int step = 0;
public static int getWIDTH() {
return WIDTH;
}
public static int getHEIGHT() {
return HEIGHT;
}
public TankFrame getTankFrame() {
return tankFrame;
}
public void setTankFrame(TankFrame tankFrame) {
this.tankFrame = tankFrame;
}
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 void paint(Graphics graphics) {
graphics.drawImage(ResourceMgr.explodes[step++],x,y,null);
if(step >= ResourceMgr.explodes.length){
tankFrame.explodes.remove(this);
}
}
}
肯定同时有好几个地方爆炸,所以爆炸也是一个集合,然后画出来,只有碰撞的时候才会爆炸,代码实现:
List explodes = new ArrayList<>(); //爆炸的集合
for(int i=0;i<explodes.size();i++){
explodes.get(i).paint(graphics);//画出爆炸
}
//在碰撞出添加爆炸
public void collidewith(Tank tank) {
if(this.group == tank.getGroup()) return;//如果当前的子弹跟坦克是一个组的就不碰撞检测。
Rectangle rect1 = new Rectangle(this.x, this.y, WIDTH, HEIGHT);
Rectangle rect2 = new Rectangle(tank.getX(), tank.getY(), Tank.WIDTH, Tank.HEIGHT);
if (rect1.intersects(rect2)) {
tank.die();
this.die();
tankFrame.explodes.add(new explode(x,y,tankFrame));
}
}
这样爆炸的效果就出来了。