In Java, I am writing a mobile application for Android to interact with some dynamic balls with some classes that I wrote myself. Gravity is determined by the tilt of the phone.
I noticed when I have a bunch of balls grouped in a corner that some of them will start to tremble or sometimes slip, while colliding with other balls. Could this be because I'm following the steps in the wrong order?
Right now I have one loop going through each ball:
- Sim iteration
- Check for collisions with other balls
- Check for conflicts with scene boundaries
I must add that I have friction with boundaries and when a ball collides with a ball, just to lose energy.
This is part of the code for how the collision occurs:
// Sim an iteration for (Ball ball : balls) { ball.gravity.set(gravity.x, gravity.y); if (ball.active) { ball.sim(); // Collide against other balls for (Ball otherBall : balls) { if (ball != otherBall) { double dist = ball.pos.distance(otherBall.pos); boolean isColliding = dist < ball.radius + otherBall.radius; if (isColliding) { // Offset so they aren't touching anymore MVector dif = otherBall.pos.copy(); dif.sub(ball.pos); dif.normalize(); double difValue = dist - (ball.radius + otherBall.radius); dif.mult(difValue); ball.pos.add(dif); // Change this velocity double mag = ball.vel.mag(); MVector newVel = ball.pos.copy(); newVel.sub(otherBall.pos); newVel.normalize(); newVel.mult(mag * 0.9); ball.vel = newVel; // Change other velocity double otherMag = otherBall.vel.mag(); MVector newOtherVel = otherBall.pos.copy(); newOtherVel.sub(ball.pos); newOtherVel.normalize(); newOtherVel.mult(otherMag * 0.9); otherBall.vel = newOtherVel; } } } } }
source share