发生冲突时如何从arrayList中删除项目?

时间:2019-06-11 05:06:55

标签: java arraylist processing collision-detection bullet

试图复制游戏《坦克麻烦》,我不知道如何对子弹和墙壁/玩家进行碰撞检测。子弹是在按下鼠标时生成的,但是当它们碰到物体时,我不知道如何使其消失。

试图让它们在接触时融入背景,但是游戏开始变得滞后。还尝试了人们用来从arrayLists中删除项目的向后循环的事情,无济于事。

PVector player = new PVector (300, 400);
ArrayList <Bullet> bullets = new ArrayList <Bullet> ();
float maxSpeed = 3; //speed of bullets

void setup() {
   size(800, 600);
   fill(0);
}

void draw() {
  background(255);
  line(20, 200, 400, 200);
  rect(300, 400, 50, 50);

  //creates an aiming tool for the players
  PVector mouse = new PVector(mouseX, mouseY);
  fill(255);
  ellipse(mouse.x, mouse.y, 8, 8);

  if (frameCount%5==0 && mousePressed) {
     PVector dir = PVector.sub(mouse, player);
     dir.normalize();
     dir.mult(maxSpeed*3);
     Bullet b = new Bullet(player, dir);
     bullets.add(b);
  }

  for (Bullet b : bullets) {
     b.update();
     b.display();
  }
}

class Bullet extends PVector {
  PVector vel;

  Bullet(PVector loc, PVector vel) {
    super(loc.x, loc.y);
    this.vel = vel.get();
  }

  void update() {
    add(vel);
  }

  void display() {
    fill(0);
    ellipse(x, y, 5, 5);
  }

  float bulletX() {
    return x;
  }
}

基本上希望子弹弹起3-4次,然后在最后一次触摸时消失。如果它在任何时候都接触到玩家,则它们都应该消失。

1 个答案:

答案 0 :(得分:1)

将方法添加到类Bullet中,该方法可以验证子弹是否在窗外:

class Bullet extends PVector {

    // [...]

    boolean outOfBounds() {
        return this.x<0 || this.x>width || this.y<0 || this.y>height;
    }
}

在类Bullet中添加带有一行的碰撞检查。要检查子弹是否碰到留置权,您必须计算直线上最近的点,并验证到直线的距离是否小于子弹的速度,以及子弹是否不会错过其侧面的直线

如果您有一条由点(O和方向(D)给出的直线,则该直线上最接近点p的点可以如下计算

X = O + D * dot(P-O, D);

2个向量的点积等于2个向量之间的夹角余弦乘以两个向量的大小(长度)。

dot( A, B ) == | A | * | B | * cos( alpha ) 

VD的点积等于直线(OD)和向量V = P - O之间的夹角余弦,乘以V的数量(长度),因为Dunit vectorD的长度是1.0),

将此代码应用于您的代码会导致以下方法:

class Bullet extends PVector {

    // [...]

    boolean collideline(float x1, float y1, float x2, float y2) {
        PVector O = new PVector(x1, y1);
        PVector L2 = new PVector(x2, y2);
        float len = O.dist(L2);
        PVector D = L2.sub(O).normalize();
        PVector P = this;
        PVector X = add(O, mult(D, sub(P, O).dot(D)));

        // distance to the line has to be less than velocity
        float distX = X.dist(P);
        if (distX > this.vel.mag())
            return false;

        // very if bullet doesn't "miss" the line
        PVector VX = X.sub(O); 
        float distO = VX.dot(D);
        return distO > -5 && distO < len+5;   
    }
}

如果项目符号超出范围或碰撞到该行,请按照其索引(相反的顺序)从列表中删除项目符号:

void draw() {

    // [...]

        for (int j = bullets.size()-1; j >= 0; j--) {
            if (bullets.get(j).outOfBounds() || bullets.get(j).collideline(20, 200, 400, 200))
                bullets.remove(j);
    }
}

相关问题