Search code examples
javascriptcollision-detectioncollision

problems in collision detection when one object is smushed between other two with greater mass


I'm trying to simulate perfect elastic collision between 3 blocks. The two on the edges have a way greater mass than the one in the center. Let's call the heavier ones h1 and h2, and the lighter l1. When they get to a position when l1 is the only thing separating the h1 and h2, l1 kind of bounces off of one of them, but then enters in the other, and it either has already checked for collisions between them or he detects the collision and gets back inside the other. I don't know how to explain it in a better way, sorry. Here's a portion of my code:

detectCollisions = function() {
    var left1 = this.x;
    var right1 = left1 + this.width;
    for (var j = 0; j < collidingThings.length; j++) {
        if (collidingThings[j] == this) continue;
        var left2 = collidingThings[j].x;
        var right2 = left2 + collidingThings[j].width;
        if (right1 > left2 && right2 > left1) {
            this.collide(collidingThings[j]);
        }
    }
}

I'm only detecting sideways collisions because for my purpose I only need that. This function is called in the update() function of each object, after it has moved. Here is function collide:

collide = function (object) {
    var m1 = this.mass;
    var m2 = object.mass;
    var v1 = this.velocity;
    var v2 = object.velocity;

    var v1f = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2);
    var v2f = ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2);

    this.x -= this.velocity;
    object.x -= object.velocity;

    this.velocity = v1f;
    object.velocity = v2f;
}

The problem is probably here, I just don't know the correct idea. I have tried a bunch of ideas which yielded to a bunch of weird results. What is happening with this is l1 bounces between h1 and h2, until in kind of breaks free, I think he get's so fast that he can move enough to completely pass one of the other two blocks, than he escapes. Any links I should read, any idea of what to do? Any help would be appreciated. Thanks


Solution

  • Answering my own question: As my scenario is simple (objects only move sideways), it's not that complicated of a situation. I don't know how the method I used here would work in other cases, eitherway. So I kinda removed that whole detectCollisions function, and did it while moving the object. Before moving anything I looped over all other colliding possibilities, and if I detected that I either collided or completelly passed an objects (here is the important part. Somethimes when the speed was too big, from one frame to the other, one object would just jump another). If any of the two are true, I just move the object as far as it can go before hitting the other, and call the collide function on them. That's basically it, my question is answered, thanks to everyone