JAVA之坦克大战(五)实现坦克与子弹的碰撞,然后消失

思路:judge1,judge方法判断敌方坦克友方子弹和友方坦克敌方子弹的碰撞,并且需要放在多线程之中判断

1.Mypanel中的run方法:
public void run()
{
    while (true)
    {
        for(int  i=0;i<enemyTanks.size();i++)
        {
            EnemyTank enemyTank = enemyTanks.get(i);
            for(int j=0;j<enemyTank.bulletVector.size();j++)
            {
                judge1(myTank,enemyTank.bulletVector.get(j));
            }
        }

        for(int i=0;i<enemyTanks.size();i++)
        {
            EnemyTank enemyTank = enemyTanks.get(i);
            for(int j=0;j<myTank.bulletVector.size();j++)
            {
                Bullet bullet = myTank.bulletVector.get(j);
                judge(enemyTank,bullet);
            }
        }
        try
        {
            Thread.sleep(50);
        }
        catch (Exception e)
        {

        }
        repaint();
    }
}

2.两个judge方法:

    public void judge(EnemyTank enemyTank,Bullet bullet)//判断子弹与EnemyTank是否碰撞
    {
        switch (enemyTank.getDir())
        {
            case 0:
            case 2:
                if(bullet.getX()>enemyTank.getX()&&bullet.getX()<enemyTank.getX()+20&&bullet.getY()>enemyTank.getY()&&bullet.getY()<enemyTank.getY()+30)
                {
                    bullet.life=false;
                    enemyTank.life=false;
                }
                break;
            case 1:
            case 3:
                if(bullet.getX()>enemyTank.getX()&&bullet.getX()<enemyTank.getX()+30&&bullet.getY()>enemyTank.getY()&&bullet.getY()<enemyTank.getY()+20)
                {
                    bullet.life=false;
                    enemyTank.life=false;
                }
        }
    }

    public void judge1(MyTank enemyTank,Bullet bullet)//判断子弹与MyTank是否碰撞
    {
        switch (enemyTank.getDir())
        {
            case 0:
            case 2:
                if(bullet.getX()>enemyTank.getX()&&bullet.getX()<enemyTank.getX()+20&&bullet.getY()>enemyTank.getY()&&bullet.getY()<enemyTank.getY()+30)
                {
                    bullet.life=false;
                    enemyTank.life=false;
                    JOptionPane.showMessageDialog(null,"游戏结束!");
                    System.exit(1);
                }
                break;
            case 1:
            case 3:
                if(bullet.getX()>enemyTank.getX()&&bullet.getX()<enemyTank.getX()+30&&bullet.getY()>enemyTank.getY()&&bullet.getY()<enemyTank.getY()+20)
                {
                    bullet.life=false;
                    enemyTank.life=false;
                    JOptionPane.showMessageDialog(null,"游戏结束!");
                    System.exit(1);
                }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值