飞机大战v4.0
相较于v3.0的改进内容:
1.增加了碰撞检测。
2.加入了音效。
飞行物父类中添加碰撞检测方法
碰撞检测方法:
public boolean isCollsion(FlyObject flyobj){
if(flyobj==null){
return false;
}
if(islive&& flyobj.isIslive()) {
//检测方法:两个矩形相交时则发生碰撞
if (this.x + this.width > flyobj.x && this.x < flyobj.x + flyobj.width && this.y + this.height > flyobj.y && this.y < flyobj.y + flyobj.height){
System.out.println("碰撞发生");
return true;
}
}
return false;
}
则在各个子类中可以使用if来做检测后的内容:在子类中加入if判断语句来使得碰撞后的对象消除
@Override
public void draw(Graphics g) {
super.draw(g);
if(isIslive())
g.fillRect(getX(),getY(),getWidth(),getHeight());
}
@Override
public void move() {
//我方战机得移动需要使用键盘来控制
if(isIslive())
super.move();
}
//上下左右操控
public void up(){
setSpeddy(-10);
}
public void down(){
setSpeddy(10);
}
public void left(){
setSpeedx(-10);
}
public void right(){
setSpeedx(10);
}
//玩家开火方法,生成子弹
public void fire(ArrayList<FlyObject> bulletList) {
if(isIslive()) {
MyBullet bullet = new MyBullet(getX() + getWidth() / 10 - 18, getY() - getHeight() / 2, 0, 10, 20, 25, Color.BLUE);
bulletList.add(bullet);
}
}
音乐播放
创建一个音乐播放类,
class MsuPlay{
AudioClip ac= null;
AudioClip ac1= null;
AudioClip ac2= null;
public MsuPlay(){
playmsu();
bgmsu();
enmymsu();
}
public AudioClip getAc(){
return ac;
}
public AudioClip getAc1(){
return ac1;
}
public AudioClip getAc2(){
return ac2;
}
//碰撞爆炸声音
public void playmsu(){
File file =new File("src/v2/music/雷火-爆炸.wav");
try {
ac = Applet.newAudioClip(file.toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
//我方子弹声音
public void bgmsu(){
File file =new File("src/v2/music/雷火-子弹1.wav");
try {
ac1 = Applet.newAudioClip(file.toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
//敌方子弹声音
public void enmymsu(){
File file =new File("src/v2/music/雷火-子弹2.wav");
try {
ac2 = Applet.newAudioClip(file.toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
调用
for (int i = 0; i < bulletList.size(); i++) {
FlyObject bullet=bulletList.get(i);
for (int j = 0; j < flyList.size(); j++) {
FlyObject enemyfight=flyList.get(j);
if(bullet.isCollsion(enemyfight)){
bullet.setIslive(false);
enemyfight.setIslive(false);
msuPlay.getAc().play();
player.score++;
break;
}
}
}
//敌方子弹和我方战机
for (int i = 0; i <enemybulletList.size() ; i++) {
FlyObject enemybullet=enemybulletList.get(i);
if(enemybullet.isCollsion(player)){
enemybullet.setIslive(false);
//调用
msuPlay.getAc().play();
player.score--;
if(player.score<=0){
player.setIslive(false);
}
}
}