使用投影将 Three.js 中的世界坐标转换为屏幕坐标 [英] Converting World coordinates to Screen coordinates in Three.js using Projection

查看:46
本文介绍了使用投影将 Three.js 中的世界坐标转换为屏幕坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几个很好的堆栈问题(12) 关于在 Three.js 中取消投影,即如何转换 (x,y) 鼠标浏览器中的坐标到 Three.js 画布空间中的 (x,y,z) 坐标.他们大多遵循这种模式:

There are several excellent stack questions (1, 2) about unprojecting in Three.js, that is how to convert (x,y) mouse coordinates in the browser to the (x,y,z) coordinates in Three.js canvas space. Mostly they follow this pattern:

    var elem = renderer.domElement, 
        boundingRect = elem.getBoundingClientRect(),
        x = (event.clientX - boundingRect.left) * (elem.width / boundingRect.width),
        y = (event.clientY - boundingRect.top) * (elem.height / boundingRect.height);

    var vector = new THREE.Vector3( 
        ( x / WIDTH ) * 2 - 1, 
        - ( y / HEIGHT ) * 2 + 1, 
        0.5 
    );

    projector.unprojectVector( vector, camera );
    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
    var intersects = ray.intersectObjects( scene.children );

我一直试图做相反的事情 - 而不是从屏幕到世界"空间,而是从世界到屏幕"空间.如果我知道 Three.js 中对象的位置,我如何确定它在屏幕上的位置?

I have been attempting to do the reverse - instead of going from "screen to world" space, to go from "world to screen" space. If I know the position of the object in Three.js, how do I determine its position on the screen?

似乎没有针对此问题的任何已发布解决方案.关于这个的另一个问题刚刚出现在 Stack 上,但是作者声称已经用一个对我不起作用的函数解决了这个问题.他们的解决方案不使用投影射线,而且我很确定由于 2D 到 3D 使用 unprojectVector(),因此 3D 到 2D 解决方案将需要 projectVector().

There does not seem to be any published solution to this problem. Another question about this just showed up on Stack, but the author claims to have solved the problem with a function that is not working for me. Their solution does not use a projected Ray, and I am pretty sure that since 2D to 3D uses unprojectVector(), that the 3D to 2D solution will require projectVector().

Github 上也有这个问题.

There is also this issue opened on Github.

感谢任何帮助.

推荐答案

试试这个:

var width = 640, height = 480;
var widthHalf = width / 2, heightHalf = height / 2;

var vector = new THREE.Vector3();
var projector = new THREE.Projector();
projector.projectVector( vector.setFromMatrixPosition( object.matrixWorld ), camera );

vector.x = ( vector.x * widthHalf ) + widthHalf;
vector.y = - ( vector.y * heightHalf ) + heightHalf;

这篇关于使用投影将 Three.js 中的世界坐标转换为屏幕坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆