我的粒子在处理过程中没有以正确的方式相互作用,这是为什么?

My particles don't interact in the right way in processing, why can this be?

我正在做一个更大的项目,当它们彼此靠近时,是否需要相互作用。该程序非常简单。当球相互接触时,或者中心彼此之间的距离比它们的组合半径更近时,它们会改变颜色。然而,球现在随机改变颜色,我不知道为什么。这些对象有一个包含所有对象的 Arraylist,因此它们可以交互并且它们是一个大的 class,用作粒子生成器。

Box box;

void setup() {
    size(1000,1000);
    box = new Box(20);
}

void draw() {
    background(255);
    box.run();
}

对象

class Object {
    int on;
    PVector loc = new PVector(500,500);
    boolean detect = false;
    PVector v;
    ArrayList<Object> others = new ArrayList<Object>();

    Object(int nin) {
        this.on = nin;
        this.loc = this.loc.add(PVector.random2D().mult(100));
        this.v = PVector.random2D();
    }

    void move() {
        loc.add(PVector.random2D().limit(5));
    }

    void detect() {
        for(int i = 0; i<others.size(); i++) {

          if(i != on) {
              Object o = others.get(i);
              float distance = sqrt(sq(o.loc.x-this.loc.x)+sq(o.loc.y - this.loc.y));
              if(distance < 100) {
                  detect = true;
              }
              else {
                detect = false;
              }
            }
        }
    }

    void display() {
        if(detect == false) {
            noFill();
        }
        if(detect == true) {
            fill(200);
        }
        stroke(50);
        ellipse(loc.x,loc.y, 50,50);
        fill(0);
        text(on, loc.x, loc.y);
    }
}

生成器

class Box {
    int n;
    ArrayList<Object> objects = new ArrayList<Object>();

    Box(int nin) {
        this.n = nin;
        for(int i = 0; i<n; i++) {
            objects.add(new Object(i));
        }
        for(int i = 0; i< objects.size();i++) {
            Object x =  objects.get(i);
            x.others = this.objects;
        }
    }

    void run() {
        for(Object i : objects) {
            i.move();
            i.detect();
            i.display();
        }
    }
}

问题是方法中的循环 detect int class Object:

for(int i = 0; i<others.size(); i++) {
    if(i != on) {
        Object o = others.get(i);
        float distance = sqrt(sq(o.loc.x-this.loc.x)+sq(o.loc.y - this.loc.y));
        if(distance < 100) {
            detect = true;
        }
        else {
            detect = false;
        }
    }
}

变量detect在循环的每次迭代中设置。因此,在循环终止后,detect 的状态取决于列表 others 中的最后一个元素。结果完全相同,因为您只计算列表的最后一个元素。

如果detect的值变为真,则中断循环。例如:

class Object {
    // [...]

    void detect() {
        detect = false;     
        for(int i = 0; i < others.size() && !detect; i++) {
            if(i != on) {
                Object o = others.get(i);
                float distance = sqrt(sq(o.loc.x-this.loc.x)+sq(o.loc.y - this.loc.y));
                detect = distance < 50;
            }
        }
    }

    // [...]
}

注意,ellipse()的第三个和第四个参数是椭圆的宽和高,所以最小距离是50,而不是100。