Question

I've looked at this question:

Mouse / Canvas X, Y to Three.js World X, Y, Z

and have implemented it in my code, the problem is that I can't seem to get it to work as others have stated.

I need to place an object in front of the camera via X and Y screen coords, not necessarily from the mouse.

This object will be at a specified distance in front of the camera, either from a pre-defined maximum distance or a calculated object distance.

Note: My Camera can be at any position in my scene and facing any direction

Here is my code:

this.reticlePos.x = 500;
this.reticlePos.y = 300;
this.reticlePos.z = 0.5;

this.projector.unprojectVector(this.reticlePos, this.camera);

//check for collisions, if collisions set distance to collision distance
var distance = this.RETICLE_RADIUS;

var direction = new THREE.Vector3( 0, 0, -1 );
direction.applyQuaternion( this.camera.quaternion );

this.rayCaster.set(this.camera.position, direction);
var collisionResults = this.rayCaster.intersectObjects(this.sceneController.obstacles);

if( collisionResults.length !== 0 ) {
    // console.log('Ray collides with mesh. Distance :' + collisionResults[0].distance);
    distance = collisionResults[0].distance - 20;
}

// set the reticle position
var dir = this.reticlePos.clone().sub( this.camera.position ).normalize();

var pos = this.camera.position.clone().add( dir.multiplyScalar( distance ) );

this.reticleMesh.position.copy( pos );

As you can see is is very similar to the linked question, yet I cannot see the object in front of my camera.

Any insight into this would be greatly appreciated.

Was it helpful?

Solution

I figured out the answer myself for anyone that checks this question later on.

To get my screen coordinates I needed to convert some input data from a gyroscope, and didn't realize that I still needed to do the following to my calculated screen coordinates:

this.reticlePos.x = ( this.reticlePos.x / window.innerWidth ) * 2 - 1;
this.reticlePos.y = - ( this.reticlePos.y / window.innerHeight ) * 2 + 1;

After doing this, everything works as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top