簡體   English   中英

無法在3D JavaScript中檢測到碰撞

[英]Can't detect collision in 3D JavaScript

我正在使用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),但由於它似乎沒有用,所以我認為這是不正確的。 另外,當我確實將其保持為“ <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()行https://puu.sh/uG1eS.png 球不斷地來回運動,但是它們彼此之間的距離甚至都不遙遠,所以我不知道為什么要檢測到碰撞

每個球都會相互碰撞。 您需要排除i === current

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM