ArrayList中的类互相更新属性

时间:2018-12-17 15:41:49

标签: java libgdx

我正在LibGDX中创建小型烟花模拟。我有一个名为particles的ArrayList,它正在填充它:

for (int i = 0; i < 2; i++) {
    Particle p = new Particle();
    p.position = position;
    p.velocity.x = MathUtils.random(-1f, 1f);
    p.velocity.y = MathUtils.random(-1f, 1f);

    particles.add(p);
}

然后在更新循环中:

for (int i = 0; i < particles.size(); i++) {
    System.out.println(i + " " + particles.get(i).position.toString() + " + " + particles.get(i).velocity.toString() + " = ");
    particles.get(i).update();
    System.out.println("    " + particles.get(i).position.toString());
 }

粒子更新功能:

velocity.add(acceleration);
position.add(velocity);

acceleration.set(0, 0);

速度是随机的,每个粒子都有独特的速度,但位置相同。输出如下: 0 (300.0,620.91364) + (-0.94489133,-0.45628428) = (299.0551,620.45734) 1 (299.0551,620.45734) + (0.3956585,0.5208683) = (299.45078,620.9782) 0 (299.45078,620.9782) + (-0.94489133,-0.45628428) = (298.5059,620.5219) 1 (298.5059,620.5219) + (0.3956585,0.5208683) = (298.90155,621.0428) 0 (298.90155,621.0428) + (-0.94489133,-0.45628428) = (297.95667,620.5865) 1 (297.95667,620.5865) + (0.3956585,0.5208683) = (298.35233,621.10736)
首先是粒子索引,位置,速度,然后是输出位置。

为什么要使用另一个粒子的位置?我试图弄清楚,但我做不到。

1 个答案:

答案 0 :(得分:5)

在for循环中,您填充ArrayList的行是:

p.position = position;

我不知道position的来源,但是这里所有的粒子都指向相同的地方。

您必须为每个粒子创建一个新的位置

p.position = new Position(x, y);

如果position是粒子的起点,则可以编写:

p.position = new Position(position.x, position.y);
相关问题