无法在3D JavaScript中检测到碰撞

时间:2017-03-12 21:41:15

标签: javascript three.js collision

我正在使用three.js来模拟布朗运动,我被困在一个需要让小分子相互碰撞的部位。这就是我到目前为止所做的:

function intersects(sphere, other){  //check if the distance between one sphere and the other is less than radius of both (4)
    var distance = Math.sqrt((sphere.position.x - other.position.x) * (sphere.position.x - other.position.x) +
                             (sphere.position.y - other.position.y) * (sphere.position.y - other.position.y) +
                             (sphere.position.z - other.position.z) * (sphere.position.z - other.position.z));
    if(distance < (4)){
         return true;
    } else {
         return false;
    }
}

function checkCollision(current){
    for(var i = 0; i < balls.length; i++) {
        if(intersects(balls[current], balls[i]) == true){
//          balls[current].velocity.negate();
            alert('hey');
        }
    }
}

当我运行代码时,我确定球不会相互碰撞/交叉,但是我不断得到警告框。我试图检查它是否小于(sphere.radius + other.radius)但我不认为这是正确的,因为它似乎不起作用。当我确实保持它'&lt; 4',它会影响性能,并且开始以大约5 fps或更低的速度慢慢运行。 checkCollision在动画期间在这里使用,所以基本上它每次都会检查它。

function animate(){
    for(var i = 0; i < balls.length; i++){
        balls[i].position.add(balls[i].velocity);
        checkWallBoundaries(i);
        checkCollision(i);
    }

    THREEx.WindowResize(renderer, camera);
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
    controls.update();
    stats.update();
}

我不知道为什么我不能让这个工作。如果有人可以帮助我,那将非常感激。

编辑:这是我取消注释球[current] .velocity.negate()line https://puu.sh/uG1eS.png时会发生什么的图片。球继续前后移动,但它们甚至不能彼此靠近,所以我不知道为什么会发现碰撞

1 个答案:

答案 0 :(得分:0)

每一个球都与自身发生碰撞。您需要排除i === current

for(var i = 0; i < balls.length; i++) {
    if(current === i) continue;
    if(intersects(balls[current], balls[i]) == true){
        alert('hey');
    }
}
相关问题