任务4 我方坦克发射子弹
按住空格,发射子弹 -----键盘的事件监听,按住空格,出现子弹,子弹绘制,坐标,方向,速度,
定义子弹类
public class shot {
private int x;
private int y;
private int direction;
private int speed=4;
public shot(int x,int y,int direction) {
super();
this.x=x;
this.direction=direction;
this.y=y;
}
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 getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
在MyTank类中添加drawShot方法
public void drawShot(int x,int y,int direction) {
switch(direction) {
case 1:
myshot=new shot(x+10,y-2,1);
break;
case 2:
myshot=new shot(x+32,y+10,2);
break;
case 3:
myshot=new shot(x+10,y+32,3);
break;
case 4:
myshot=new shot(x-2,y+10,4);
break;
}
}
在GamePanel类中的键盘事件中添加监听
if(e.getKeyCode()==KeyEvent.VK_SPACE){
my.drawShot(my.getX(),my.getY(),my.getDirection());
}
当调用paint方法时绘制出子弹,故在paint方法里添加drawShot();(由于一开始子弹是不绘制的,故在MyTank类中声明 shot myshot=null;)然后在paint方法里做一个判断,若myshot不为空,执行drawShot(); 代码如下:
if(my.myshot!=null) {
g.setColor(Color.RED);
g.drawOval(my.myshot.getX()-1,my.myshot.getY(),3,3);
}
效果图:
至此,实现一个静止的子弹,下一任务便是让子弹飞起来(线程)