在three.js所相机和地形的碰撞(camera and terrain collision on

2019-11-01 14:25发布

I have a building model created with sketchup, exported as collada file and loaded to three.js with colladaloader. Everything works fine except that the camera can pass through walls. How do I prevent this? So far I have tried with Raycasting, but I think something is wrong.

this is how the model is loaded

loader.options.convertUpAxis = true;
loader.load( 'model/cityhall.dae', function ( collada ) {

dae = collada.scene;
skin = collada.skins[ 0 ];
model_geometry = collada.scene.children[ 0 ].children[0].geometry;
model_material = collada.scene.children[ 0 ].children[0].material;

dae.scale.x = dae.scale.y = dae.scale.z = 1;
dae.updateMatrix();
scene.add( dae );
dae.traverse(function (child) {
if (child instanceof THREE.Mesh) {
                        objects.push(child);
                    }
                });
            });

the raycaster

            rayFloor = new THREE.Raycaster();
            rayFloor.ray.direction.set( 0, -1, 0 );

            rayWall = new THREE.Raycaster();
            rayWall.ray.direction.set(0,0,1);

this is for the animation

            function animate() {
            requestAnimationFrame( animate );

            controls.isOnObject( false );
                            controls.isWallCollision( false);

            rayFloor.ray.origin.copy( controls.getObject().position );
            rayFloor.ray.origin.x -= 10;

            rayWall.ray.origin.copy( controls.getObject().position );
            rayWall.ray.origin.y -= 8;

            var intersections = rayFloor.intersectObjects( objects );
            var intersections2 = rayWall.intersectObjects( objects );

            if ( intersections.length > 0 ) {
                //console.log('floor' + intersections);

                var distance = intersections[ 0 ].distance;
                if ( distance > 0 && distance < 10 ) {
                    controls.isOnObject( true );
                }

            }

            if ( intersections2.length > 0 ) {
                //console.log('wall' + intersections);

                var distance = intersections2[ 0 ].distance;
                if ( distance > 0 && distance < 10 ) {
                    controls.isWallCollision( true );
                }

            }
            controls.update( Date.now() - time );
            render();

            time = Date.now();
        }

the problem is it cannot detect wall and floor correctly.

Answer 1:

下面是使用Raycaster碰撞检测的工作示例的链接:

http://stemkoski.github.com/Three.js/Collision-Detection.html

希望能帮助到你!



文章来源: camera and terrain collision on three.js