【问题标题】:threejs raycasting - intersections between camera and a loaded obj modelthreejs raycasting - 相机和加载的 obj 模型之间的交集
【发布时间】:2015-03-23 17:44:00
【问题描述】:

我正在通过包含我已加载为网格的 obj 的场景移动相机,并且我想检测相机是否与我的 obj 的任何墙壁发生碰撞。

我的代码基于这个 threejs 示例:http://threejs.org/examples/misc_controls_pointerlock.html,并尝试在此处应用您的示例:http://stemkoski.github.io/Three.js/Collision-Detection.html - 但我似乎无法发生冲突。

我的例子是here

相关的javascript是here:

如果有人能指出如何检测碰撞的正确方向,我将不胜感激。这是相关的代码:

var objects = [];

var oLoader = new THREE.OBJLoader();
  //oLoader.load('models/chair.obj', function(object, materials) {
    oLoader.load('models/model-for-threejs.obj', function(object, materials) {

    // var material = new THREE.MeshFaceMaterial(materials);
    var material = new THREE.MeshLambertMaterial({ color: 0x000000 });
    //var material = new THREE.MeshBasicMaterial({wireframe: true});


    object.traverse( function(child) {
      if (child instanceof THREE.Mesh) {
        //objects.push(child); //MH - not sure if the object needs to be added here or not, but if I do, this really bogs down things down
      }
    });

    object.position.x = 0;
    object.position.y = 12;
    object.position.z = 0;

    scene.add(object);

    objects.push(object);


  });
}

var curPos = controls.getObject().position; //gives the position of my camera

    raycaster.ray.origin.copy( curPos );
    //raycaster.ray.origin.y -= 10; 
    raycaster.ray.origin.z +=10; //guessing here, but since I'm moving in 2d space (z / x), maybe I should be moving my ray ahead in z space?


    var intersections = raycaster.intersectObjects( objects ); //

    var isOnObject = intersections.length > 0;

    if (isOnObject){ console.log('collide' }; //MH - nothing happening here

【问题讨论】:

    标签: javascript three.js webgl collision-detection raycasting


    【解决方案1】:

    Raycaster 的相交对象采用带有子对象的 Object3D,并有一个用于递归的标志。

    https://github.com/mrdoob/three.js/blob/master/src/core/Raycaster.js#L33

    所以它应该是这样的:

    var intersections = raycaster.intersectObjects( yourRootObject3D, true );
    

    【讨论】:

    • 谢谢 - 即使使用递归,它似乎也不起作用(虽然肯定会减慢速度) - 我一定做错了什么。我不清楚 objloader 是否默认创建 Object3D - 这可能是问题吗?
    • 如果场景中有很多对象,递归光线投射可能会很昂贵。您可以通过只给它一个子集来过滤它,或者使用更智能的方法来过滤,例如空间细分。我会用一条线来检查你的光线投射光线并绘制它以进行调试
    猜你喜欢
    • 2017-09-10
    • 2020-11-01
    • 2014-12-10
    • 2019-06-26
    • 2021-01-15
    • 2018-05-21
    • 1970-01-01
    • 2014-04-02
    • 2019-04-23
    相关资源
    最近更新 更多