How to separate two colliding circles?
I'm looking to separate two colliding circles, to push them back equally by the minimum amount so that they're perfectly separated.
I have this so far:
var totalRadius : Number = _circle1.radius + _circle2.radius;
var x : Number = _circle1.position.x - _circle2.position.x;
var y : Number = _circle1.position.y - _circle2.position.y;
var distanceSquared : Number = (x * x) + (y * y);
if (distanceSquared < totalRadius * totalRadius)
{
var distance : Number = Math.sqrt(distanceSquared);
var separation : Number = totalRadius - distance;
// No idea what to do now!
}
That much I've figured out so far. So I know a collision has occurred and I know that each circle is separation
amount into each other (so I guess divide by 2 to separate them equally).
The problem is that separation doesn't have any implied directionality and I don't know what to do. I can't just do circ开发者_运维知识库le1.position -= separation / 2; circle2.position += separation / 2
because that'll move both the X and Y axis equally.
How do I add directionality to separation
?
Thanks!
Use unit vector to move both circles by separation / 2
.
unitVector = (circle1.Position - circle2.Position) / distance
circle1.Position += unitVector * seperation / 2
circle2.Position -= unitVector * seperation / 2
Edit:
just change seperation / 2
and/or +-
part. It will allow you to move it by any distance you want.
精彩评论