I am working on a particle simulation using Box2D with Processing.
The setup: I generate 4 kinds of particles that exist in equal amounts (for instance 200 in total, 50 each). They are (for now) randomly moving inside a box, each edge of the box is made of a static boundary. The Particles should bounce off each other as well as all 4 boundaries. This works fine.
Now I am working with the collisionListeners.beginContact()
function to make different things happen when different particles collide. My problem occurs in the following case: when two particles of the same kind collide, they should produce a particle of another kind at the location of their collision with an added velocity of their previous velocities. In most cases, this is working well! However, in about 15% of the cases, it does not: sometimes the new particle is not generated at the location of their collision, but at the world center point (0,0)
, or rather at the center of the processing canvas if speaking in pixels (width/2,height/2)
. This results in particles randomly shooting out of the center point of the canvas, which is not what I want. And even worse, they tend to stack up on top of each other causing errors.
I do not know why this is happening, I am suspecting it might have something to do with collisions that happen very close to the boundaries so that there is some kind of tunnelling effect that teleports them to the center? But I have no real clue...
I am getting the location of the collision inside beginContact()
through this process:
// assign objects to colliding particles
Fixture f1 = c.getFixtureA();
Fixture f2 = c.getFixtureB();
Body b1 = f1.getBody();
Body b2 = f2.getBody();
Object o1 = b1.getUserData();
Object o2 = b2.getUserData();
// get velocity for new particle
Vec2 velB1 = b1.getLinearVelocity();
Vec2 velB2 = b2.getLinearVelocity();
Vec2 addedVel = velB1.add(velB2);
// get collision coordinates in pixel values
WorldManifold worldManifold = new WorldManifold ();
c.getWorldManifold(worldManifold);
Vec2 collPointPx = box2d.coordWorldToPixels(worldManifold.points[0]);
The last vector collPointPx
is the one I am using when generating the new particle, and it is the vector that apparently every now and then shows (0,0)
or rather (width/2,height/2)
instead of the right location of the collision.
It would be great if anyone of you has an idea how to solve this. Maybe I am making a mistake in the code posted. Obviously, I am a beginner at this. Thank you very much!