0

I am creating small firework simulation in LibGDX. I have ArrayList called particles and this is filling it:

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);
}

And then in update loop:

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());
 }

Particle update function:

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

acceleration.set(0, 0);

Velocity is random and every particle have unique velocity but position is the same. Here is output: 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)
First is particle index, position, velocity and then output position.

Why is it using position from another particle? I am trying to figure it out but I can't.

3
  • 2
    You are reusing your position object inside your Particle class. They reference all the same position object. Check where you have new Position() in your code (assuming that's the class name), and how often this line is executed in your code.
    – Progman
    Commented Dec 17, 2018 at 15:48
  • This kind of error is very common and is one of the reasons modern coding guidelines recommend making your classes immutable. (For example, all the classes in the java.time package, introduced in Java 8, are immutable.) Commented Dec 17, 2018 at 15:57
  • @DodgyCodeException The problem with using immutable classes in Java games is that it causes GC churn, which causes little stutters in the frame rate. Java unfortunately doesn't have structs.
    – Tenfour04
    Commented Dec 18, 2018 at 14:47

1 Answer 1

5

In your for loop where you fill the ArrayList you have the line:

p.position = position;

I don't know where position comes from but here all Particles point to the same.

You must create a new Position for every Particle

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

If position is the start point for your Particles you can write:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.