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?
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.