坦克大战—day 7

实现坦克发射子弹的功能。

1.创建子弹对象

public class Bullet {
    private static final int DEFAULT_SPEED=Tank.DEFAULT_SPEED<<1;
    private static final int RADIUS=4;
    private int x,y;
    private int speed=DEFAULT_SPEED;
    private int dir;
    private int atk;
    private Color color;

    public Bullet(int x, int y, int dir, int atk, Color color) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.atk = atk;
        this.color = color;
    }


}

画子弹方法,子弹的逻辑方法,子弹的移动方法。


    public void draw(Graphics g)
    {
        logic();
        g.setColor(color);
        g.fillOval(x-RADIUS,y-RADIUS,RADIUS<<1,RADIUS<<1);

    }

    private void logic() {
        move();
    }
    private void move()
    {
        switch (dir){
            case Tank.DIR_UP:
                y-=speed;
                break;
            case Tank.DIR_DOWN:
                y+=speed;
                break;
            case Tank.DIR_LEFT:
                x-=speed;
                break;
            case Tank.DIR_RIGHT:
                x+=speed;
                break;
        }
    }

2.坦克发射子弹

fire方法是生成子弹,将生成的子弹放在集合中。在drawBullet方法中遍历集合将子弹画出来。


    /**
     *坦克发射子弹方法
     */
    public void fire()
    {
        int bulletX=x;
        int bulletY=y;
        switch (dir){
            case DIR_UP:
               bulletY-=2*RADIUS;
                break;
            case DIR_DOWN:
                bulletY+=2*RADIUS;
                break;
            case DIR_LEFT:
                bulletX-=2*RADIUS;
                break;
            case DIR_RIGHT:
                bulletX+=2*RADIUS;
                break;
        }
        Bullet bullet=new Bullet(bulletX,bulletY,dir,atk,color);
        bullets.add(bullet);
    }

    /**
     * 绘制子弹
     */
    private void drawBullet(Graphics g){
         for(Bullet bullet:bullets)
             bullet.draw(g);
    }

3.发射子弹按键处理事件

按下空格键,发射子弹。

    private void KeyEventRun(int keyCode) {
        switch (keyCode){
            case KeyEvent.VK_UP:
            case KeyEvent.VK_W:
             mytank.setDir(Tank.DIR_UP);
             mytank.setState(Tank.STATE_MOVE);
                break;
            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_S:
                mytank.setDir(Tank.DIR_DOWN);
                mytank.setState(Tank.STATE_MOVE);
                break;
            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_A:
                mytank.setDir(Tank.DIR_LEFT);
                mytank.setState(Tank.STATE_MOVE);
                break;
            case KeyEvent.VK_RIGHT:
            case KeyEvent.VK_D:
                mytank.setDir(Tank.DIR_RIGHT);
                mytank.setState(Tank.STATE_MOVE);
                break;
            case KeyEvent.VK_SPACE:
                mytank.fire();
        }
    }

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页