diff --git a/src/com/msb/Tank.java b/src/com/msb/Tank.java index 74ba32f..8efc0c6 100644 --- a/src/com/msb/Tank.java +++ b/src/com/msb/Tank.java @@ -13,6 +13,7 @@ public class Tank { private int x,y; private DirEnum dir; private static final int SPEED = 10; + private boolean move = false; public Tank(int x, int y, DirEnum dir) { this.x = x; @@ -22,6 +23,16 @@ public class Tank { public void paint(Graphics g) { g.fillRect(x, y, 50, 50); + moving(); + } + + public void setDir(DirEnum dir) { + this.dir = dir; + } + + public void moving() { + + if( ! move) return; switch (dir) { case UP: y -= SPEED; break; @@ -30,9 +41,10 @@ public class Tank { case RIGHT: x += SPEED; break; default: break; } + } - public void setDir(DirEnum dir) { - this.dir = dir; + public void setMove(boolean move) { + this.move = move; } } diff --git a/src/com/msb/TankFrame.java b/src/com/msb/TankFrame.java index eb100e6..271aeae 100644 --- a/src/com/msb/TankFrame.java +++ b/src/com/msb/TankFrame.java @@ -72,10 +72,17 @@ public class TankFrame extends Frame { case KeyEvent.VK_DOWN : bD = false; break; default: break; } -// setDir(); //通过做了实验,现阶段就算不用这个方法,也不影响,但是按键抬起,坦克应该停止,如果还按照原来的方向移动就不对了 + setDir(); } private void setDir() { + //当没有任何方向键按下的时候,那么让坦克停止 + if( !bL && !bR && !bU && !bD ) { + tank.setMove(false); + } else { + tank.setMove(true); + } + //为什么不用if-else 因为有可能是一起按两个方向键,那最后拿到哪个算哪个 if(bL) tank.setDir(DirEnum.LEFT); if(bR) tank.setDir(DirEnum.RIGHT);