thykka
thykka

Reputation: 550

Keeping circles from overlapping

I'm trying to figure out the JavaScript math to move two colliding circles apart from each other.

The left side of this image is a visual representation of what I already have:

http://i.imgur.com/FMv1G3O.png

x1, y1, x2 and y2 are the positions of the circles, r1 and r2 are the radii of the circles, theta is the angle between the circles in relation to the x-axis of the canvas.

How do I calculate the new [x,y] positions for both circles, so that they "push" each other apart as demonstrated on the right side of the image?

I'm also planning to make the smaller circle be pushed more than the larger one. That should be easy enough by using their normalized radii as a multiplier.

Upvotes: 4

Views: 1081

Answers (1)

6502
6502

Reputation: 114461

// Just take the vector difference between the centers
var dx = x2 - x1;
var dy = y2 - y1;

// compute the length of this vector
var L = Math.sqrt(dx*dx + dy*dy);

// compute the amount you need to move
var step = r1 + r2 - L;

// if there is a collision you will have step > 0
if (step > 0) {
    // In this case normalize the vector
    dx /= L; dy /= L;

    // and then move the two centers apart
    x1 -= dx*step/2; y1 -= dy*step/2;
    x2 += dx*step/2; y2 += dy*step/2; 
}

Upvotes: 7

Related Questions