Frage

I am trying to build a virtual tour inside a building (the whole building is an obj model) using three.js. Everything loads fine and the library is pretty straightforward. My most critical issue is that I can't implement collision detection with the camera, I tried using rays but I couldn't find a suitable example for my case.

My model load:

var loader = new THREE.OBJMTLLoader();
loader.addEventListener( 'load', function ( event ) {
    var newModel = event.content;
    newModel.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.castShadow = true;
            child.receiveShadow = true;
        }
    } );
    scene.add( newModel );
    objects.push( newModel );
    });
loader.load( 'model/model.obj', 'model/model.mtl' );

The camera creation (I don't know if it is relevant to the issue)

camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth / window.innerHeight,
    1,
    10000
);
camera.position.set( 0, 25, 0 );
camera.lookAt( 0, 0, 0 );

NOTE: The camera moves inside the model, I don't want to detect collision between two separate obj models, I want to detect collision (and stop the camera from passing through walls) inside one single model.

Any help will be greatly appreciated

War es hilfreich?

Lösung

Looking at the documentation for Raycaster in Three.js at http://threejs.org/docs/58/#Reference/Core/Raycaster, you can create a ray like Raycaster( origin, direction, near, far ). Perhaps for you this would look something like

var ray = new THREE.Raycaster(camera.position, cameraForwardDirection, camera.position, collisionDistance);

Where cameraForwardDirection is the direction in front of you camera. I think you can get this by doing something like:

var cameraForwardDirection = new THREE.Vector3(0,0,-1).applyMatrix4(camera.matrixWorld);

This should work because the camera points in the negative Z direction (hence the 0,0,-1) and we want to apply the orientation of the camera to this vector. This assumes you are only moving forward. If you wanted to check for collisions in other directions, you could cast rays in other directions.

collisionDistance would be the minimum distance for a collision. You can experiment with this to find what works with respect to the scale of things in your scene.

Once you have cast this ray, you will need to check for intersections. You can use the ray.intersectObject( object, recursive ) method. Since it seems like you just have that one model, it might look something like:

var intersects = ray.intersectObject(newModel, true);
if(intersects.length>0){
 // stop the camera from moving farther into the wall
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top