Threejs 光线投射不起作用 [英] threejs raycasting does not work

查看:75
本文介绍了Threejs 光线投射不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试编写单元测试以检查碰撞检测时遇到问题.我将代码简化为仅此可能 - 我在 (0, 0, 0) 中有一个平面,我从该平面上方(从 (0, 100, 0)) 到底部 (0, -1, 0) 进行光线投射,然后我假设找到与那架飞机的交点,但没有运气.

I'm having a problem trying to write a unit test to check collision detection. I simplify code as only this possible - I have a plane in (0, 0, 0) and I do raycasting from above this plane (from (0, 100, 0)) to bottom (0, -1, 0) and I suppose to find intersections with that plane but no luck.

console.clear();
var intersections,
    from = new THREE.Vector3(0, 100, 0);
    direction = new THREE.Vector3(0, -1, 0),
    raycaster = new THREE.Raycaster();

var geometry = new THREE.PlaneGeometry(10, 10, 1, 1);
var ground = new THREE.Mesh(geometry);
ground.position.set(0, 0, 0);
ground.rotation.x = THREE.Math.degToRad(-90);

raycaster.set(from, direction);
intersections = raycaster.intersectObjects([ground]);
console.log(intersections);

这里有什么问题?为什么这个简单的代码没有显示任何交集?(r73).

What is wrong here? Why this simple code does not show any intersections? (r73).

jsfiddle 示例

推荐答案

您需要在光线投射之前更新地面网格的世界变换.(通常,渲染器会在 render() 调用中为您执行此操作.)

You need to update the world transform of the ground mesh prior to raycasting. (Normally, the renderer does this for your in the render() call.)

console.clear();
var intersections,
    from = new THREE.Vector3(0, 100, 0);
    direction = new THREE.Vector3(0, -1, 0),
    raycaster = new THREE.Raycaster();

var geometry = new THREE.PlaneGeometry(10, 10, 1, 1);
var ground = new THREE.Mesh(geometry);
ground.position.set(0, 0, 0);
ground.rotation.x = THREE.Math.degToRad(-90);

ground.updateMatrixWorld(); // add this

raycaster.set(from, direction);
intersections = raycaster.intersectObjects([ground]);
console.log(intersections);

three.js r.73

three.js r.73

这篇关于Threejs 光线投射不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆