欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-16 18:37:28
...

思路: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);
                }
        }
    }