0

Trying to get two balls to collide and bounce back at appropriate angles. When the balls collide however they get stuck together and I have no idea what I'm doing wrong here.

I'm calling this checkCollision() function within my animate function Obviously cx is ball1 xpos, cx2 is ball2 xpos. Same for cy.

function checkCollision () {
    var dx = cx2 - cx;  // distance between x
    var dy = cy2 - cy;  // distance between y
    var distance = Math.sqrt(dx * dx + dy * dy); 

    if (distance < (radius1 + radius2)) {
        // Collision detected. Find the normal.
        var normalX = dx / distance;
        var normalY = dy / distance;

        //find the middle point of the distance
        var midpointX = (cx + cx2)/2;
        var midpointY = (cy + cy2)/2;

        //bounce back
        cx = midpointX - radius1*normalX;
        cy = midpointY - radius1*normalY;
        cx2 = midpointX - radius2*normalX;
        cy2 = midpointY - radius2*normalY;

        var dVector = (vx - vx2) * normalX;
        dVector += (vy - vy2) * normalY;

        var dvx = dVector * normalX;
        var dvy = dVector * normalY;

        vx -= dvx;
        vy -= dvy;
        vx2 += dvx;
        vy2 += dvy;
    }
    ...

I've never done much/any vector work. Is there any easier way to do this? How would I write this with angles instead?

joshuaaron
  • 810
  • 1
  • 15
  • 27
  • Why do you subtract the velocity of the normal vector from the current velocity? Shouldn't you just set the velocity equal to the velocity of the normal vector? Like this `vx = dvx; vy = dvy;` – mpallansch May 21 '15 at 02:39
  • 1
    It could be that your balls are stuck in an infinite state of collision (wow, that sounded strange). – Niddro May 21 '15 at 06:18
  • well to be honest @mpadittech I'm not 100% my friend helped me write this it's not my forte at all, i tried your way and the balls got stuck on collision as well though. – joshuaaron May 21 '15 at 13:37

1 Answers1

0

You need to use some basic maths to detect the intersection between two circles.

A similar problem is described here:

algorithm to detect if a Circles intersect with any other circle in the same plane

There is a C# sample that could be easily adapted to Javascript.

Community
  • 1
  • 1
garryp
  • 5,508
  • 1
  • 29
  • 41