2D simple ball collision vector

爷,独闯天下 提交于 2019-12-25 06:23:50

问题


Trying to get two balls to collide and bounce back at appropriate angles. When the balls collide however they get stuck together and I have no idea what I'm doing wrong here.

I'm calling this checkCollision() function within my animate function Obviously cx is ball1 xpos, cx2 is ball2 xpos. Same for cy.

function checkCollision () {
    var dx = cx2 - cx;  // distance between x
    var dy = cy2 - cy;  // distance between y
    var distance = Math.sqrt(dx * dx + dy * dy); 

    if (distance < (radius1 + radius2)) {
        // Collision detected. Find the normal.
        var normalX = dx / distance;
        var normalY = dy / distance;

        //find the middle point of the distance
        var midpointX = (cx + cx2)/2;
        var midpointY = (cy + cy2)/2;

        //bounce back
        cx = midpointX - radius1*normalX;
        cy = midpointY - radius1*normalY;
        cx2 = midpointX - radius2*normalX;
        cy2 = midpointY - radius2*normalY;

        var dVector = (vx - vx2) * normalX;
        dVector += (vy - vy2) * normalY;

        var dvx = dVector * normalX;
        var dvy = dVector * normalY;

        vx -= dvx;
        vy -= dvy;
        vx2 += dvx;
        vy2 += dvy;
    }
    ...

I've never done much/any vector work. Is there any easier way to do this? How would I write this with angles instead?


回答1:


You need to use some basic maths to detect the intersection between two circles.

A similar problem is described here:

algorithm to detect if a Circles intersect with any other circle in the same plane

There is a C# sample that could be easily adapted to Javascript.



来源:https://stackoverflow.com/questions/30363537/2d-simple-ball-collision-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!