Search code examples
javascriptgeometrygame-physicscollision

Slow the movement of circle collision resolution


I have written a collision detection and resolution system for the game I am currently working on. The collision resolution doesn't work quite as intended though. Occasionally I spawn one circle inside of the other, when this happens I'd like the inside circle to slowly move out of the other's diameter, but currently the code that I have working does it quite quickly and jarringly. It instantly teleports outside of the circle, rather than a slow transition.

I know that the code I am currently using tells the circle where it SHOULD be, so I just need to slowly move the circle to that position. But that is proving to be difficult.

I've tried a couple of solutions, one is included in the code below. I have also tried using linear interpolation to move the circle to its current position, to where the collision algorithm is telling it it should be. That didn't work correctly either.

//r is the radius of the circle
var dx = cell.x - cell2.x;
var dy = cell.y - cell2.y;
var distance = Math.sqrt(dx * dx + dy * dy);

if (distance < cell.r + cells2.r && cell.r > cells2.r){
var unitX = dx/distance;
var unitY = dy/distance;

cell.x = cells2.x + (cell.r + cells2.r + 1) * unitX;
cell.y = cells2.y + (cell.r + cells2.r + 1) * unitY;
//Ive tried below, but the results were not correct.
//cell.x += (cells2.x + (cell.r + cells2.r + 1) * unitX)*0.5;
//cell.y += (cells2.y + (cell.r + cells2.r + 1) * unitY)*0.5;
}

Solution

  • To move cell apart from cell2, you don't need to add cells2 coordinates

     cell.x += (cell.r + cells2.r + 1) * unitX;
    

    To move slowly, make speed smaller

    //calculate once:
    v = 0.01 * (cell.r + cells2.r - distance);
    // at every step:
    cell.x += v * unitX;