user1812896
user1812896

Reputation:

Three.js How to Get Accurate World Coordinates when Renderer is in a div and not the whole window

I am using the three.js framework and have the renderer in a div that takes up the right 50% of the screen and has 87.5% height. I am then trying to place a sphere wherever is clicked, however the coordinates that are calculated are not accurate within the div and the spheres appear in various positions away from the mouse. How can I accurately calculate the coordinates within this div? Thanks and here's the code

function onDocumentMouseMove( event ) {
    event.preventDefault();
    mouseX = (event.clientX / container.offsetWidth) * 2 - 1;
    mouseY = -(event.clientY / container.offsetHeight) * 2 - 1;
}

function onDocumentMouseDown(event){
    event.preventDefault()
    alert("X: " + mouseX + " Y: " + mouseY);
    var vector = new THREE.Vector3( mouseX, mouseY, 1 );
    var sphere = new THREE.Mesh(new THREE.SphereGeometry(size / 4), new THREE.MeshLambertMaterial(intensity));  
    sphere.position.x = vector.x;
    sphere.position.y = vector.y;
    sphere.position.z = vector.z;
    scene.add(sphere);
    spheres.push(sphere);
}

Upvotes: 1

Views: 3069

Answers (1)

Alex Under
Alex Under

Reputation: 1489

Ok, so first of all - you have to set properly you camera inside your div:

camera = new THREE.PerspectiveCamera( 45, referenceToYourDiv.width / referenceToYourDiv.height, 1, 1000 );

Then, all you have to do is to calculate your mouse event relative to you div's position.

The thing is that in THREE.js you deal with absolute center of your container to get (0,0) coordinates in 3D space, but in HTML - your (0,0) is located in the corner of your screen. So just "move" that (0,0) point to your container's center and you're good to go!

If you would have fullscreen rendering, than your code would be:

mouseX = event.clientX - windowHalfWidth;
mouseY = event.clientY - windowHalfHeight;

But since you deal with custom size container, try this out:

mouseX = (event.clientX - (window.innerWidth*0.5))-(container.width*0.5);
mouseY = (event.clientY - (window.innerHeight*0.875))-(container.height*0.5);

For window width 1920 and container's width 50% - it will produce mouse values from -480 to +480, regarding to your container's width center.

For window height 1200 and container's height 87.5% - it will produce mouse values from -525 to +525, regarding to your container's height center.

Well, at least it should - I didn't try this code, but that is the basic idea of what you have to do.

Hope that helps.

UPDATE: Here is an example of what you are trying to achieve: http://jsfiddle.net/PwWbT/

Upvotes: 1

Related Questions