course3 碰撞检测

master
Jian Hu 3 years ago
parent a213dc71d5
commit d77b7b1ed2

Binary file not shown.

@ -57,6 +57,19 @@ public class Bullet {
}
}
//检测是否跟坦克碰撞
public void collideWith(Tank tank){
Rectangle bulletRect = new Rectangle(x, y, WIDTH, HEIGHT);
Rectangle tankRect = new Rectangle(tank.getX(), tank.getY(), Tank.WIDTH, Tank.HEIGHT);
if(bulletRect.intersects(tankRect)){
tank.die();
this.die();
}
}
private void die() {
this.live = false;
}
public int getX() {
return x;

@ -5,6 +5,10 @@ import java.io.IOException;
public class MainV3 {
public static void main(String[] args) throws InterruptedException, IOException {
TankFrameV3 tf = new TankFrameV3();
for(int i = 0; i < 5; i++){
tf.enemyTanks.add(new Tank(50 + i*80, 200, Direction.DOWN, tf));
}
while (true){
Thread.sleep(50);
tf.repaint();

@ -7,6 +7,7 @@ public class Tank {
private Direction dir;
private static final int SPEED = 10;
private boolean moving;
private boolean living = true;
private TankFrameV3 tankFrame;
public static final int WIDTH = ResourceManager.tankD.getWidth();
public static final int HEIGHT = ResourceManager.tankD.getHeight();
@ -20,6 +21,7 @@ public class Tank {
}
public void paint(Graphics g) {
if(!living) tankFrame.enemyTanks.remove(this);
//根据方向绘制坦克
switch (dir){
case UP:
@ -55,6 +57,10 @@ public class Tank {
}
}
public void die(){
this.living = false;
}
public int getX() {
return x;
}
@ -87,6 +93,14 @@ public class Tank {
this.moving = moving;
}
public boolean isLiving() {
return living;
}
public void setLiving(boolean living) {
this.living = living;
}
public void fire() {
int bx = x + Tank.WIDTH/2 - Bullet.WIDTH/2;
int by = y + Tank.HEIGHT/2 - Bullet.HEIGHT/2;

@ -16,10 +16,11 @@ public class TankFrameV3 extends Frame {
Tank tank = new Tank(500, 500, Direction.UP, this);
// Bullet bullet = new Bullet(520, 440, Direction.UP);
List<Bullet> bullets = new ArrayList();
List<Tank> enemyTanks = new ArrayList<>();
public TankFrameV3(){
setVisible(true);
setBounds(200, 200 , GAME_WIDTH, GAME_HEIGHT);
setBounds(500, 200 , GAME_WIDTH, GAME_HEIGHT);
setResizable(false);
setTitle("tank war");
this.addKeyListener(new MyKeyListener());
@ -51,12 +52,24 @@ public class TankFrameV3 extends Frame {
Color color = g.getColor();
g.setColor(Color.WHITE);
g.drawString("当前子弹数量:" + bullets.size(), 60, 50);
g.drawString("当前敌人数量:" + enemyTanks.size(), 60, 80);
g.setColor(color);
tank.paint(g);
for(int i = 0; i< enemyTanks.size(); i++){
enemyTanks.get(i).paint(g);
}
for (int i = 0; i< bullets.size(); i++){
bullets.get(i).paint(g);
}
for(int i = 0; i< bullets.size(); i++){
for(int j=0; j< enemyTanks.size(); j++){
bullets.get(i).collideWith(enemyTanks.get(j));
}
}
// for(Iterator<Bullet> it = bullets.iterator(); it.hasNext();){
// Bullet b = it.next();
// if(!b.isLive()){

Loading…
Cancel
Save