1

I am a visual learner working on a simple 2D game that requires balls to bounce off of each other with no spin.

I have followed the code in many links and chose to use the example found at Ball to Ball Collision - Detection and Handling

My code however results in both the ball accelerating out of control and also somehow removing balls from the playing field on striking. If someone could describe my errors to me that would be much appreiated. However I would find just as much help in step by step pictures describing the math behind the collisions found in the link above.

public void resolveCollision2(PoolBall ball) {

    vector delta = new vector(getXPos() - ball.getXPos(), getYPos() - ball.getYPos());
    float d = (float) delta.getMagnitude();
    vector mtd = delta.scalerMultiply((32.0 - d) / d);
    vector reset = mtd.scalerMultiply(0.5);

    XPos = XPos + reset.getXlen();
    YPos = YPos + reset.getYlen();

    ball.setXPos(ball.getXPos() - reset.getXlen());
    ball.setYPos(ball.getYPos() - reset.getYlen());

    vector v1 = new vector(getXVel(), getYVel());
    vector v2 = new vector(ball.getXVel(), ball.getYVel());

    vector v = v1.subtract(v2);
    float vn = v.dot(mtd.normalize());

    if(vn > 0.0f) return;

    float i = (-(1.0f + 0.1f) * vn);
    vector impulse = mtd.scalerMultiply(i);

    vector v1prime = v1.add(impulse);
    vector v2prime = v2.subtract(impulse);

    setXVel(Math.sqrt(v1prime.getXlen()));
    setYVel(Math.sqrt(v1prime.getYlen()));


    ball.setXVel(Math.sqrt(v2prime.getXlen()));
    ball.setYVel(Math.sqrt(v2prime.getYlen()));

}


public void poolBallPoolBallCollision() {

    double XDif = 0.0;
    double YDif = 0.0;
    double XDif2 = 0.0;
    double YDif2 = 0.0;

    for (int i = 0; i < 15; i++) {  
        for (int j = i + 1; j < 15; j++) {  
            if (colliding(ballList[i], ballList[j])) {
                ballList[i].resolveCollision2(ballList[j]);
            }
        }
    }
}

Things to note

  • balls have equal mass
  • no friction
  • no spin
Community
  • 1
  • 1
  • I apologize for stackOverflow formatting issues this is the first time I have been so desperate. Criticism welcome :) – BriBri12497 May 27 '14 at 23:30
  • No worries, I've fixed the formatting. It's generally a good idea to set your IDE of choice to turn tabs into spaces for just this kind of thing. :) – Casey May 27 '14 at 23:46
  • thank you, now I just need a hero to help me with the java/coding/physics part! – BriBri12497 May 27 '14 at 23:52

0 Answers0