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);
}
}
}
上一篇: C#碰撞(Collision)与触发(Trigger)检测
下一篇: Android代码中加解密方式