# TankWar 单机（JAVA版）版本0.7~0.9 让坦克实现8个方向的移动

2016-10-08

```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;

}

}```

A点的横坐标等于二分之根号2*ptLength.

A点的纵坐标等于二分之根号2*ptLength.

```// 炮塔长度

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);```

```// 我方坦克的键盘松下事件

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;

}

}```