2013-08-19 199 views
0

我正在使用three.js創建一個webgl遊戲,現在我成功地進行了碰撞檢測,但是我需要在碰撞後從場景中移除碰撞的物體,我該怎麼做?Three.js碰撞並移除碰撞對象

我基本上遵循本教程

http://webmaestro.fr/blog/basic-collisions-detection-with-three-js-raycaster/

在這裏,我把我的障礙變量的所有障礙,這裏是我的代碼。

function collide(){ 
    'use strict'; 

    var collisions, i, 
    // Maximum distance from the origin before we consider collision 
    distance = 32, 
    // Get the obstacles array from our world 
    obstacles = getObstacles(); 
    // For each ray 
    for (i = 0; i < rays.length; i += 1) { 
     // We reset the raycaster to this direction 
     caster.set(objectHolder.position, rays[i]); 
     // Test if we intersect with any obstacle mesh 
     collisions = caster.intersectObjects(obstacles); 
     // And disable that direction if we do 
     if (collisions.length > 0 && collisions[0].distance <= distance) { 

      // Yep, this.rays[i] gives us : 0 => up, 1 => up-left, 2 => left, ... 
      if ((i === 0 || i === 1 || i === 7) && direction.z === 1) { 
       // direction.setZ(0); 

       console.log("hit!!! up upleft left"); 

      } else if ((i === 3 || i === 4 || i === 5) && direction.z === -1) { 
       // direction.setZ(0); 

       console.log("hit!!! i 3 i 4 i 5"); 
      } 
      if ((i === 1 || i === 2 || i === 3) && direction.x === 1) { 
       // direction.setX(0); 

       console.log("hit!!! i 1 i 2 i 3 x 1"); 
      } else if ((i === 5 || i === 6 || i === 7) && direction.x === -1) { 
       // direction.setX(0); 

       console.log("hit!!!"); 
      } else if (i === 0 || direction.z === 1){ 
       console.log("hit!!!"); 
      } 
     } 
    } 

} 

這裏是得到障礙函數我這樣做,我基本上有兩個多維數據集對象,並與障礙串聯:

function getObstacles(){ 
    return obstacles.concat(cube, cube2); 
} 

現在我如何刪除特定的多維數據集時對象選手對象擊中它。 如果有的話,你能否建議在我的代碼中碰撞檢測的更好方法。

光線投射代碼是這樣的。

var rays = [ 
       new THREE.Vector3(0, 0, 1), 
       new THREE.Vector3(1, 0, 1), 
       new THREE.Vector3(1, 0, 0), 
       new THREE.Vector3(1, 0, -1), 
       new THREE.Vector3(0, 0, -1), 
       new THREE.Vector3(-1, 0, -1), 
       new THREE.Vector3(-1, 0, 0), 
       new THREE.Vector3(-1, 0, 1) 
     ]; 
var caster = new THREE.Raycaster(); 

從哪裏可以得到關於Three.js中使用的類或方法的更多信息,如光線投射?

+0

試試這裏:http://threejs.org/docs/。雖然上次我查了只有完成了。另外,我還會添加一些前段時間我碰到的碰撞代碼。即使我記得沒錯,我也使用了Raycaster。 – zozo

+0

是的,但我找不到有用的東西,或可能是我沒有得到它 – monk

+0

我怎麼知道什麼是碰撞變量的屬性..我試圖collisions.mesh,或碰撞[0]或碰撞[我]並試圖做.. scene.remove(碰撞[我]),但它沒有工作 – monk

回答

2

回答你的第一個問題。一旦raycaster返回相交對象數組你簡單地傳遞所述第一對象到scene.remove作爲這樣

scene.remove(collisions[0].object); 

至於碰撞檢測推移,有許多不同的方法。 Raycasting是目前在Three.js中實現的方法。查看Three.js示例和文檔頁面:http://threejs.org/docs/#Reference/Core/Raycaster。文檔有一些差距,但是對於像這樣的核心特性非常有用。

編輯:剛纔看到的評論,是的一些文件是不完整的。但是在每個文檔頁面的底部都有一個通常非常有用的.js文件的鏈接。在這種情況下,您會注意到Raycaster.js函數返回具有以下結構的相交數組對象。

intersects.push({ 
    distance: distance, 
    point: intersectionPoint, 
    face: null, 
    faceIndex: null, 
    object: object 
}); 

所以至少你可以訪問距離,點,面(如果適用),faceIndex(如果適用)和對象:)希望有所幫助。

+0

謝謝你幫助我很多 – monk