坦克静止-在无按方向键的情况下,让坦克停下来

Network
bingor_yhj 2 years ago
parent a721578f24
commit 5606e45574

@ -13,6 +13,7 @@ public class Tank {
private int x,y; private int x,y;
private DirEnum dir; private DirEnum dir;
private static final int SPEED = 10; private static final int SPEED = 10;
private boolean move = false;
public Tank(int x, int y, DirEnum dir) { public Tank(int x, int y, DirEnum dir) {
this.x = x; this.x = x;
@ -22,6 +23,16 @@ public class Tank {
public void paint(Graphics g) { public void paint(Graphics g) {
g.fillRect(x, y, 50, 50); g.fillRect(x, y, 50, 50);
moving();
}
public void setDir(DirEnum dir) {
this.dir = dir;
}
public void moving() {
if( ! move) return;
switch (dir) { switch (dir) {
case UP: y -= SPEED; break; case UP: y -= SPEED; break;
@ -30,9 +41,10 @@ public class Tank {
case RIGHT: x += SPEED; break; case RIGHT: x += SPEED; break;
default: break; default: break;
} }
} }
public void setDir(DirEnum dir) { public void setMove(boolean move) {
this.dir = dir; this.move = move;
} }
} }

@ -72,10 +72,17 @@ public class TankFrame extends Frame {
case KeyEvent.VK_DOWN : bD = false; break; case KeyEvent.VK_DOWN : bD = false; break;
default: break; default: break;
} }
// setDir(); //通过做了实验,现阶段就算不用这个方法,也不影响,但是按键抬起,坦克应该停止,如果还按照原来的方向移动就不对了 setDir();
} }
private void setDir() { private void setDir() {
//当没有任何方向键按下的时候,那么让坦克停止
if( !bL && !bR && !bU && !bD ) {
tank.setMove(false);
} else {
tank.setMove(true);
}
//为什么不用if-else 因为有可能是一起按两个方向键,那最后拿到哪个算哪个 //为什么不用if-else 因为有可能是一起按两个方向键,那最后拿到哪个算哪个
if(bL) tank.setDir(DirEnum.LEFT); if(bL) tank.setDir(DirEnum.LEFT);
if(bR) tank.setDir(DirEnum.RIGHT); if(bR) tank.setDir(DirEnum.RIGHT);

Loading…
Cancel
Save