思路:添加子弹类,并且写出子弹运行的线,然后在Mytank中添加新的fire()方法,用于发射子弹时获得当前炮管的方向,因为子弹较多所以需要把子弹放在Vector集合里,并且需要开多线程,因为子弹运动需要进行重绘,所以就需要Panel开多线程。
1.Bullet类:
public class Bullet implements Runnable{ //多线程
private int speed=10;
private int dir;
boolean life=true;
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getDir() {
return dir;
}
public void setDir(int dir) {
this.dir = dir;
}
public void run()//重写runnable 接口重点额run方法
{
while (true)//子弹一直飞
{
//JAVA特有异常抛出
switch (getDir())//子弹坐标改变(移动)
{
case 0:
setY(getY()-getSpeed());
break;
case 1:
setX(getX()-getSpeed());
break;
case 2:
setY(getY()+getSpeed());
break;
case 3:
setX(getX()+getSpeed());
break;
}
if(getX()<0||getY()<0||getX()>1200||getY()>1000)
{
life=false;
break;
}
//判断是否过边界如果过边界了那么子弹的生命就没了
try//程序正常时执行
{
Thread.sleep(50);//让程序暂停50ms
}
catch (Exception e)//非正常时执行
{
}
}
}
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;
}
private int x;
private int y;
Bullet(int x,int y,int dir)//子弹需要构造函数直接给方向赋值
{
this.x=x;
this.y=y;
this.dir=dir;
}
}
2.MyTank中的新方法fire():
public void fire()//装弹
{
switch (this.getDir())
{
case 0:
bullet = new Bullet(this.getX()+8,this.getY()-7,0);
bulletVector.add(bullet);
break;
case 1:
bullet = new Bullet(this.getX()-7,this.getY()+8,1);
bulletVector.add(bullet);
break;
case 2:
bullet = new Bullet(this.getX()+8,this.getY()+30,2);
bulletVector.add(bullet);
break;
case 3:
bullet = new Bullet(this.getX()+30,this.getY()+8,3);
bulletVector.add(bullet);
break;
}
Thread thread = new Thread(bullet);
thread.start();
}
3.MyPanel中添加的线程
public void run()
{
while (true)
{
try
{
Thread.sleep(50);
}
catch (Exception e)
{
}
repaint();
}
}