本文共 3319 字,大约阅读时间需要 11 分钟。
public Tank(int x, int y, TankClient tc) { //tc是为了能够调用fire this(x, y); this.tc = tc; }tc.m=fire();也是创建tc的目的(持有对方的引用,用构造方法进行初始化),主类里面也要进行改动
Missile m = null; Image offScreenImage = null; public void paint(Graphics g) { if(m!=null) m.draw(g); myTank.draw(g); }如果没有则不打出子弹(下一个版本将要解决的问题)
case KeyEvent.VK_CONTROL:tc.m = fire();break; //case穿透,如果不加的话
2.坦克里面fire方法(坦克要打出子弹) 返回子弹对象m(子弹应该在中点位置打出,还有静止的时候,子弹也静止打出) 添加常量:高度与宽度 坦克 public static final int WIDTH =30;public static final int HEIGHT =30;子弹
public static final int WIDTH =10;public static final int HEIGHT =10;坦克打出的位置计算:
public Missile fire() { int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2; int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2; Missile m = new Missile(x, y, dir); return m; }总结:本版本最主要对象是子弹,子弹打出及方向控制,位置等等。tc的创建,应该重 点理解,持有对方引用,然后通过构造方法初始化,然后赋值 tc.m = fire(); 下一版本:创建炮筒,解决禁止子弹无运动方向的问题。 附上坦克类的代码(本版本主要改到类)
public class Tank { public static final int XSPEED =5; public static final int YSPEED =5; public static final int WIDTH =30; public static final int HEIGHT =30; TankClient tc; int x,y; private boolean bL=false,bU=false,bD=false,bR=false; enum Direction {L,LU,U,RU,R,RD,D,LD,STOP}; private Direction dir = Direction.STOP; public Tank(int x,int y){ this.x=x; this.y=y; } public Tank(int x,int y,TankClient tc){ this(x,y); this.tc=tc; } void move(){ switch(dir){ case L: x -= XSPEED;break; case LU: x -= XSPEED; y -= XSPEED;break; case U: y -= XSPEED;break; case RU: x += XSPEED;y -= XSPEED;break; case R: x += XSPEED;break; case RD: x += XSPEED;y += XSPEED;break; case D: y += XSPEED;break; case LD: x -= XSPEED;y += XSPEED;break; } } public void draw(Graphics g) { Color c = g.getColor(); g.setColor(Color.RED); g.fillOval(x, y, WIDTH, HEIGHT); g.setColor(c); move(); } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); switch(key){ case KeyEvent.VK_CONTROL: tc.m = fire(); break; case KeyEvent.VK_LEFT: bL=true; break; case KeyEvent.VK_UP: bU=true; break; case KeyEvent.VK_RIGHT: bR=true; break; case KeyEvent.VK_DOWN: bD=true; break; } locateDirection(); } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); switch(key){ case KeyEvent.VK_LEFT: bL=false; break; case KeyEvent.VK_UP: bU=false; break; case KeyEvent.VK_RIGHT: bR=false; break; case KeyEvent.VK_DOWN: bD=false; break; } locateDirection(); } void locateDirection(){ if(bL && !bU && !bR && !bD)dir=Direction.L; else if(bL && bU && !bR && !bD)dir=Direction.LU; else if(!bL && bU && !bR && !bD)dir=Direction.U; else if(!bL && bU && bR && !bD)dir=Direction.RU; else if(!bL && !bU && bR && !bD)dir=Direction.R; else if(!bL && !bU && bR && bD)dir=Direction.RD; else if(!bL && !bU && !bR && bD)dir=Direction.D; else if(bL && !bU && !bR && bD)dir=Direction.LD; else if(!bL && !bU && !bR && !bD)dir=Direction.STOP; } public Missile fire(){ int x=this.x+Tank.WIDTH/2-Missile.HEIGHT/2; int y=this.y-Missile.WIDTH/2+Tank.HEIGHT/2; Missile m = new Missile(x, y, dir); return m; }}
转载地址:http://clrxb.baihongyu.com/