运行结果:
版本0.7的项目要求是将坦克单独封装为一个类 在前面我们一直就是按照把坦克封装承类实现的。所以这里就不再写了。
然后就是版本0.8和版本0.9了 控制坦克八个方向移动。
首先说一下思路:
我们可以设置四个方向的boolean变量 然后根据键盘事件 来判断你按了哪个键来使对应方向的booelan值设置为true
然后根据方向的boolean值来判断方向,最后根据方向来移动坦克。
首先在枚举变量中添加LD(左下),LU(左上),RD(右下),RU(右上)
然后在Tank类中添加记录按键的四个布尔变量
在Tank的键盘事件中为四个布尔变量赋值
然后就是根据方向的boolean值来判断当前要移动的方向
判断完方向后就是坦克的移动了。为了保证向LU,LD,RD,RU移动的长度和L,R,U,D移动的长度相同 speed*根号2/2
private void move() {
if (curDir == Direction.D) {
y += speed;
}
if (curDir == Direction.U) {
y -= speed;
}
if (curDir == Direction.L) {
x -= speed;
}
if (curDir == Direction.R) {
x += speed;
}
if (curDir == Direction.LU) {
y -= Math.sqrt(2) * speed / 2;
x -= Math.sqrt(2) * speed / 2;
}
if (curDir == Direction.LD) {
y += Math.sqrt(2) * speed / 2;
x -= Math.sqrt(2) * speed / 2;
}
if (curDir == Direction.RU) {
y -= Math.sqrt(2) * speed / 2;
x += Math.sqrt(2) * speed / 2;
}
if (curDir == Direction.RD) {
y += Math.sqrt(2) * speed / 2;
x += Math.sqrt(2) * speed / 2;
}
if (curDir != Direction.STOP) {
ptDir = curDir;
}
}
做完了这些 还要记得根据方向重新绘制坦克的炮塔。因为在上面我们只计算了四个方向的
如图:如果1是朝上的炮塔,3是右上的炮塔,2是右上的炮塔
因为1,2,3三个炮塔的长度是相同的ptLength。那么2炮塔上A点的坐标和1,3有什么关系呢?
假设1,2,3相交的点为坐标原点,根据勾股定理我们可以得到:
A点的横坐标等于二分之根号2*ptLength.
A点的纵坐标等于二分之根号2*ptLength.
同理,左上,左下,右下也可以得到对应A点的坐标。
具体代码:
// 炮塔长度
int ptLength = 50;
// 画一条线 通过坦克的坐标计算炮杆的坐标
Line2D l2 = null;
if (ptDir == Direction.U)
l2 = new Line2D.Double(x + width / 2, y + height / 2,
x + width / 2, y + height / 2 - ptLength);
if (ptDir == Direction.D)
l2 = new Line2D.Double(x + width / 2, y + height / 2,
x + width / 2, y + height / 2 + ptLength);
if (ptDir == Direction.L)
l2 = new Line2D.Double(x + width / 2, y + height / 2, x + width / 2
- ptLength, y + height / 2);
if (ptDir == Direction.R)
l2 = new Line2D.Double(x + width / 2, y + height / 2, x + width / 2
+ ptLength, y + height / 2);
if (ptDir == Direction.RU)
l2 = new Line2D.Double(x + width / 2, y + height / 2, x + width / 2
+ Math.sqrt(2) * ptLength / 2, y + height / 2
- Math.sqrt(2) * ptLength / 2);
if (ptDir == Direction.RD)
l2 = new Line2D.Double(x + width / 2, y + height / 2, x + width / 2
+ Math.sqrt(2) * ptLength / 2, y + height / 2
+ Math.sqrt(2) * ptLength / 2);
if (ptDir == Direction.LD)
l2 = new Line2D.Double(x + width / 2, y + height / 2, x + width / 2
- Math.sqrt(2) * ptLength / 2, y + height / 2
+ Math.sqrt(2) * ptLength / 2);
if (ptDir == Direction.LU)
l2 = new Line2D.Double(x + width / 2, y + height / 2, x + width / 2
- Math.sqrt(2) * ptLength / 2, y + height / 2
- Math.sqrt(2) * ptLength / 2);
做完了这些,一定不要忘记最后一步啊 。在松下了键盘时把对应的方向boolean值设置为false。否则你的坦克会朝一个方向移动。
// 我方坦克的键盘松下事件
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
up = false;
break;
case KeyEvent.VK_DOWN:
down = false;
break;
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_RIGHT:
right = false;
break;
default:
break;
}
}
代码难免有bug 欢迎提出 一起优化 慢慢来~
从这里开始我把所有代码都上传到百度云把。不然篇幅太大了。
全部代码点击下载