问题
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.
回答1:
Here is a link to a working example of collision detection using Raycaster:
http://stemkoski.github.com/Three.js/Collision-Detection.html
Hope it helps!
来源:https://stackoverflow.com/questions/14931687/camera-and-terrain-collision-on-three-js