mrdoob/three.js — Issue #899: screen to world coordinates using unprojectVector()
Author: q-depot
Created: 2011-12-13 16:59:23+00:00
State: open

Hi guys,

I'm trying to transform screen and world coordinates, following other discussions on this forum I've implemented two methods to move between coordinates systems, when I move from world to screen and back to world everything works, however when I try to specify the coordinates on screen and then move to world, something goes wrong, looks like it depends on the z value, but I couldn't figure it out.

The code below generates this output:

screen pos 1048.701096854919 259.13967094352427 0.980097507238161
test.php:193world pos(func) 49.99999999999974 14.99999999999994 0.5000000000003425
test.php:199screen to world -3.211103130368165 0.5946487278459565 96.00119964010797

var pos = new THREE.Vector3(50, 15, 0.5);	// world pos

pos = worldToScreen(pos);
console.log ( "screen pos " + pos.x + " " + pos.y + " " + pos.z );

pos = screenToWorld(pos);	// this call returns the correct values
console.log ( "world pos(func) " + pos.x + " " + pos.y + " " + pos.z );

// this bit doesn't work.
pos = new THREE.Vector3(500, 260, 0.5);	// screen pos
pos = screenToWorld(pos);
console.log ( "screen to world " + pos.x + " " + pos.y + " " + pos.z );

function screenToWorld(_screenPos)
{
var worldPos = _screenPos.clone();
worldPos.x = worldPos.x / windowHalfX - 1;
worldPos.y = - worldPos.y / windowHalfY + 1;
projector.unprojectVector( worldPos, camera );
return worldPos;
}

function worldToScreen(_worldPos)
{
var screenPos = _worldPos.clone();
projector.projectVector( screenPos, camera );
screenPos.x = ( screenPos.x + 1 ) * windowHalfX;
screenPos.y = ( - screenPos.y + 1) * windowHalfY;
return screenPos;
}

thanks.