javascript collision detection between drawable circles

匆匆过客 提交于 2019-11-30 19:19:32

The problem you are facing is totally unrelated to the underlying rendering techinique. This is just a math problem.

What you basically want to do for your situation is calculate the distance between the ball you drag and any ball on the table. If the distance is too short a collision happened.

For two objects this is simple, you need three values: The x and y coordinates of the balls and their radii.

var ball = {
    x: 100,
    y: 100
    r: 10
};

To calculate the distance you do this:

var squareX = Math.pow(Math.abs(ballA.x - ballB.x), 2);
var squareY = Math.pow(Math.abs(ballA.y - ballB.y), 2);
var hypothenuse = Math.sqrt(squareX + squareY);
var distance = hypothenuse - ballA.r - ballB.r;

if (distance >= 0) {
    // new position is valid
}

Since you have a number of balls on a pool table you need to call this code once for each ball on the table that is not moved to compare all of them.

function canMove(ballA, ballB) {
    var squareX = Math.pow(Math.abs(ballA.x - ballB.x), 2);
    var squareY = Math.pow(Math.abs(ballA.y - ballB.y), 2);
    var hypothenuse = Math.sqrt(squareX + squareY);
    var distance = hypothenuse - ballA.r - ballB.r;

    if (distance >= 0) {
        return true;
    }
    return false;
}


function canDrag(ball, balls) {
    var isMovable = true;
    for (var i = balls.length-1; i >= 0; i--) {
        isMovable = canMove(ball, balls[i]);
        if (!isMovable) {
            return false;
        }
    }
    return true;
}

In the last snippet I assumed that your ball objects are stored in the balls array. I hope this helps.

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