Javascript - collision around circle problem

I am making a game in HTML5, Canvas, and this is my code for resolving a collision between two moving circles:

function resCCCol(a, b) {
    var dx = a.x - b.x;
    var dy = a.y - b.y;

    var dist = dx * dx + dy * dy;

    var vx = b.vx - a.vx;
    var vy = b.vy - a.vy;

    var dot = dx * vx + dy * vy;

    if (dot > 0) {
        var scale = dot / dist;

        var cx = dx * scale;
        var cy = dy * scale;

        var mass = a.r + b.r;

        var cw1 = 2 * b.r / mass;
        var cw2 = 2 * a.r / mass;

        a.vx += cw1 * cx
        a.vy += cw1 * cy
        b.vx -= cw2 * cx
        b.vy -= cw2 * cy
    }
}

If I set the coordinates so that the circles overlap, but still have their speed as 0, the circles will not push each other, this is a problem. How to fix it?

EDIT: Fiddle: http://jsfiddle.net/yP7xf/2/ , click "Fail!". to see the failure, as you see, they will not separate.

+2
source share
3 answers

, dot ( , ), , dist < sum(radii). , , , , .

+2

, resCCCol() , dot - 0. if dot >= 0, 0 .

if (dot > 0) { //dot === 0
    var scale = dot / dist; //scale === 0

    var cx = dx * scale; //cx === 0
    var cy = dy * scale; //cy === 0

    var mass = a.r + b.r;

    var cw1 = 2 * b.r / mass;
    var cw2 = 2 * a.r / mass;

    a.vx += cw1 * cx // 0
    a.vy += cw1 * cy // 0
    b.vx -= cw2 * cx // 0
    b.vy -= cw2 * cy // 0
}

, dot === 0. - , 0:

if (dot > 0) { 
    ... 
} else {
    a.vx = 1;
    a.vy = 1;
    b.vx = -1;
    b.vy = -1;
}

, , , -, ( , ).

+2

, , , , (, ), - dot === 0, , . :

if (dot === 0) {
    // numbers pulled completely out of thin air...
    a.vx = 0.5;
    a.vy = 0.5;
    b.vx = -0.5;
    b.vy = -0.5;
}

http://jsfiddle.net/yP7xf/5/

What speed should you give them? This is what you will need to work out. You probably want them to diverge so that you can calculate some vector based on a line from the center of one to the center of the other, and send one in one direction along this vector and the other in the other at any speed that you think is appropriate. But if they lie exactly one above the other (centers at the same point), then you will also have to consider this case.

0
source

Source: https://habr.com/ru/post/1627374/


All Articles