Three.js中的Raycasting不起作用

时间:2014-06-20 22:04:40

标签: three.js

我已经看到了很多关于这个主题的问题,但每当我尝试使其适应我的情况时,它就永远不会有效。

为什么当我点击球体(saphi_mesh)时,ray.intersectObject(saphi_mesh)会返回一个空数组?

我在这里想念的是什么?

JSFiddle:http://jsfiddle.net/qZh59/

init函数:

container = document.createElement("div")
document.body.appendChild(container)

camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000)
camera.position. z = 500

scene = new THREE.Scene()

var ambientLight = new THREE.AmbientLight(0xbbbbbb);
scene.add(ambientLight);

var floor_geo =  new THREE.PlaneGeometry(window.innerWidth, 5, 10, 10)
var floor_color = new THREE.MeshBasicMaterial({color: 0xffff00})
var floor_mesh = new THREE.Mesh(floor_geo, floor_color)
var saphi_material = new THREE.MeshBasicMaterial({color: 0xfff000})
var saphi_geo = new THREE.SphereGeometry(50, 50, 50)
saphi_mesh = new THREE.Mesh(saphi_geo, saphi_material)
scene.add(saphi_mesh)
scene.add(floor_mesh)

projector = new THREE.Projector()

renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)

container.appendChild(renderer.domElement)

renderer.domElement.addEventListener("mousedown", onClick, false)

onClick功能:

x = (event.clientX / window.innerWidth) * 2 - 1
y = (event.clientY / window.innerHeight) * 2 + 1
dir = new THREE.Vector3(x, y, -1)
projector.unprojectVector(dir, camera)
console.log(dir)    
ray = new THREE.Raycaster(camera.position, dir.sub(camera).normalize())
console.log(ray.intersectObject(saphi_mesh))

1 个答案:

答案 0 :(得分:0)

我刚刚更正了onClick功能

function onClick(event) {
    x = (event.clientX / window.innerWidth) * 2 - 1;
    y = -(event.clientY / window.innerHeight) * 2 + 1;
    dir = new THREE.Vector3(x, y, -1)
    dir.unproject(camera)

    console.log(dir)    
    ray = new THREE.Raycaster(camera.position
                           ,dir.sub(camera.position).normalize()
          )
    console.log(ray.intersectObject(saphi_mesh))
}

以下是工作示例:http://jsfiddle.net/qZh59/2/