jthomas
jthomas

Reputation: 858

How do I draw two circles whose edges meet?

In a <canvas> element, I'm animating a collection of circles that can collide with one another. Occasionally these collisions occur between iterations of the main loop, and on the next iteration the loops are "inside" each other.

To combat this, I've calculated the point of impact (C) between the two circles, and now wish to nudge the circles' coordinates so that their edges meet on this point of impact. I've been playing around with inverting their velocities to move them away from each other along their original vectors, but I can't seem to get it right.

How do I calculate the "nudged" coordinates of A and B so their edges meet at C?

Diagram of collision

Upvotes: 0

Views: 130

Answers (1)

markE
markE

Reputation: 105015

A demo: http://jsfiddle.net/m1erickson/VtM7F/

enter image description here

Here's how:

var dx=C.x-A.x;
var dy=C.y-A.y;
var angleC=Math.atan2(dy,dx);

var newAX=C.x+A.radius*Math.cos(angleC-PI);
var newAY=C.y+A.radius*Math.sin(angleC-PI);

And do the same with B.

Upvotes: 2

Related Questions