0

Here's jsfiddle example of what I want to see. Mouse moving over screen. Somewhere in the World drawn some 3d object EXACTLY behind the cursor.

http://jsfiddle.net/ksRyQ/3551/

unp = p.unprojectVector(new THREE.Vector3(  mx - (window.innerWidth/2), (window.innerHeight/2)-my, 0), camera)
//console.log(unp)
cur.position.x = unp.x;
cur.position.y = unp.y;
cur.position.z = unp.z/10; // dunno how to draw object with unp.z - it's too far and invisible

Why that sphere appears in some different location? What could be done for correct drawings here?

Vasiliy Stavenko
  • 1,116
  • 1
  • 12
  • 27

1 Answers1

0

Projector.unprojectVector() maps from normalized device coordinate space (NDC space) to world space. The mapping is not linear. If the z-coordinate of the point you are projecting is 1, then the projected point will be mapped to the back-plane of the camera's frustum. Therefore, use a number slightly less than 1, like 0.999.

Here is the pattern you need to use

vector.set( ( mx / window.innerWidth ) * 2 - 1, - ( my / window.innerHeight ) * 2 + 1, 0.999 );

p.unprojectVector( vector, camera );

cur.position.copy( vector );

If you want more control over the z-component of the projected point, you can select any point on the line segment between the camera position and the projected point computed above.

Fiddle: http://jsfiddle.net/ksRyQ/3566/

three.js r.63

WestLangley
  • 92,014
  • 9
  • 230
  • 236
  • Could you please explain transformation of screen coordinates to vector's `X` and `Y`. That's perfectly works, but I have no idea why. – Vasiliy Stavenko Nov 22 '13 at 04:40
  • In my case I need world coordinates to produce line (camera -> unprojected point) For shooting something. I don't know Is THREE provides something simplier for such tasks? – Vasiliy Stavenko Nov 22 '13 at 04:45
  • You need to study on your own to understand how projections work. See http://stackoverflow.com/questions/11966779/should-i-start-learning-webgl-or-use-three-js/11970687#11970687 for excellent sources. You also need to study the relevant three.js source code. Study `Raycaster` examples for how to "shoot something". – WestLangley Nov 22 '13 at 15:05