I'm trying to create a collision between two circles (c1: player moves and c2: static object) and put in the shortest possible distance, away when there is overlap. The below code works, but inaccurately because always push horizontally and vertically: http://postimg.org/image/ik15bv6s1/
Does anyone know the right algorithm to do this?
var distance = Math.sqrt(Math.pow(c1.x - c2.x, 2) + Math.pow(c1.y - c2.y, 2));
// r1, r2 = radius
// Collision test
if (distance <= (r1 + r2)) {
var distanceToMove = (r1 + r2) - distance;
if (c1.x < c2.x) {
c1.x -= distanceToMove;
} else {
c1.x += distanceToMove;
}
if (c1.y < c2.y) {
c1.y -= distanceToMove;
} else {
c1.y += distanceToMove;
}
}