坦克大战Java项目四

任务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);
			}

效果图:

至此,实现一个静止的子弹,下一任务便是让子弹飞起来(线程)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值