简体   繁体   中英

Can't detect collision in 3D JavaScript

I am using three.js to make a simulation of the Brownian Motion and I'm stuck on a part where I need to get the little molecules to collide against each other. This is what I have so far:

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');
        }
    }
}

When I run the code, I know for certain that the balls don't collide/intersect with each other, however I continuously get an alert box. I've tried to check if it's less than (sphere.radius + other.radius) but I don't think that's correct since it didn't seem to work. Also when I do keep it '< 4', it messes up the performance and it starts to run slowly at around 5 fps or less. checkCollision gets used here during the animation, so basically it checks it every time.

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();
}

I don't know why I can't get this to work. If someone could help me, that'd be greatly appreciated.

edit: Here's a picture of what happens when I uncomment the balls[current].velocity.negate() line https://puu.sh/uG1eS.png . The balls keep going back and forth but they're not even remotely close to each other, so I don't know why collision is being detected

Every ball collides with itself. You need to exclude i === current

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM