Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting click position on a sphere's texture with ThreeJS

Currently: I have a sphere with a texture on it that rotates around the y axis. I also have the position that was clicked in 3D space, as well as the rotated position on the sphere (I think).

Goal: Get the position on the texture, for example: I want to get what square of the image I click on. (See Example Sphere and image below)


In practice, I won't be using this image but I felt it would be a good starting point.

Code For getting position on the sphere based on this example:

function onDocumentMouseDown( event ) {
    event.preventDefault();
    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( objects );
    if ( intersects.length > 0 ) {
        console.log(intersects[ 0 ].point);
        var vector = new THREE.Vector3( 1, 0, 0 );

        var axis = new THREE.Vector3( 0, 1, 0 );
        var angle = objects[ 0 ].rotation.y;

        //Rotate Point
        intersects[ 0 ].point = vector.applyAxisAngle( axis, angle );

        console.log(intersects[ 0 ].point);
    }
}

Sphere:

Sphere

Image Wrapping it: Image Wrap

like image 493
Chris Avatar asked Jan 28 '16 21:01

Chris


1 Answers

Actually, you don't need to calculate anything. intersects[0].uv gives you the the UV coordinates.

Texture coordinates range always from 0.0 to 1.0. They are unitless. So same texture with another resolution will fit as well. UV coordinates

So, if you need to know the pixel position of your click, do:

var pixelX = Math.round(intersects[0].uv.x * textureWidth);
var pixelY = Math.round(intersects[0].uv.y * textureHeight);
like image 135
Brakebein Avatar answered Oct 16 '22 23:10

Brakebein