html5 canvas elastic collision squares

后端 未结 2 1903
礼貌的吻别
礼貌的吻别 2021-01-13 13:52

I am re-asking this question since I did not make myself clear in what I wanted in my last question.

Does anyone know how to do elastic collision or handle collision

2条回答
  •  灰色年华
    2021-01-13 14:13

    The answer is actually quite simple: swap the velocities of each block when they collide. That's it! Also for your collision test change RectA.x to just x, since they are normal variables given:

        function collides(rectA, rectB) {
          return !(x + rectA.width < x2 ||
           x2 + rectB.width < x ||
           y + rectA.height < y2 ||
           y2 + rectB.height < y);
          }; 
    

    And swapping velocities:

            if(collides(drawing, drawing2)){
                var t = vx; var t2 = vy;
                vx = vx2; vy = vy2;
                vx2 = t; vy2 = t2;
            };
    

    And after those small changes we have working elastic collisions: http://jsfiddle.net/Y7MFq/11/

提交回复
热议问题