Webgl基於Three.js的開發——利用Frustum來判斷相交或者包含
阿新 • • 發佈:2018-11-06
首先來看一下Frustum的文件:Frustum幫助文件
根據文件建立一個Frustum:
function initFrustum() { //定義錐形物體最遠的四個點 var topLeftPoint = new THREE.Vector3(-2000,2000,-1000); var topRightPoint= new THREE.Vector3(2000,2000,-1000); var bottomLeftPoint = new THREE.Vector3(-2000, -2000, -1000); var bottomRightPoint = new THREE.Vector3(2000, -2000, -1000); //定義錐形物體最近的四個點 var nearTopLeftPoint = new THREE.Vector3(-2000, 2000, 1000); var nearTopRightPoint = new THREE.Vector3(2000, 2000, 1000); var nearBottomLeftPoint = new THREE.Vector3(-2000, -2000, 1000); var nearBottomRightPoint = new THREE.Vector3(2000, -2000, 1000); topPlane = new THREE.Plane(); bottomPlane = new THREE.Plane(); rightPlane = new THREE.Plane(); leftPlane = new THREE.Plane(); nearPlane = new THREE.Plane(); farPlane = new THREE.Plane(); topPlane.setFromCoplanarPoints(nearTopLeftPoint, topLeftPoint, topRightPoint); leftPlane.setFromCoplanarPoints(nearTopLeftPoint, topLeftPoint, bottomLeftPoint); bottomPlane.setFromCoplanarPoints(nearBottomLeftPoint, bottomLeftPoint, bottomRightPoint); rightPlane.setFromCoplanarPoints(nearBottomRightPoint, bottomRightPoint, topRightPoint); farPlane.setFromCoplanarPoints(topLeftPoint, topRightPoint, bottomLeftPoint); nearPlane.setFromCoplanarPoints(nearTopLeftPoint,nearTopRightPoint,nearBottomLeftPoint); frustum = new THREE.Frustum(topPlane,leftPlane,bottomPlane,rightPlane,farPlane,nearPlane); }
接著前面兩章,把判斷選中的改為:
frustum.intersectsObject(intersects[0].object)
就可以直觀的看到相交的結果。
最後可以直觀的看到結果:相交的時候返回True.從原始碼中可以看到相交和包含返回一樣的值。如果想把相交和包含區分開來,需要進一步處理。另外,這裡的結果不一定正確,這裡是取的是包含物體sphere,所以有些情況下,實際沒有相交,會被判斷為相交。