使用three.js提取3D点的2D屏幕位置 [英] extracting the 2D screen position of a 3D point with three.js

查看:509
本文介绍了使用three.js提取3D点的2D屏幕位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何获得3D点的2D屏幕坐标。

I am trying to figure out how to get the 2D screen coordinates for a 3D point.

我正在使用three.js生成一些雪花,这些雪花会慢慢掉落屏幕。我最初将脚本编写为2D画布动画,并添加了鼠标交互功能,因此您可以通过鼠标移动来吹雪。效果很好,但是当切换到webgl时,雪花现在被表示为3D点,并且由于鼠标到每个粒子的距离越来越远,由于视角的原因,粒子从屏幕中心的距离表现出了不希望的行为。

I am using three.js to generate some snowflakes that fall slowly down the screen. I originally wrote the script just as a 2d canvas animation and added mouse interaction so you could blow the snow around with mouse movement. It worked well, but when switching to webgl the snowflakes were now represented as 3D points and getting the distance of the mouse to each particle makes particles further from the center of the screen behave in an undesired way because of the perspective.

http://www.simplemathguild.com/snowtest.html

推荐答案

您需要做的是通过viewProjection矩阵转换worldPos vec3,然后执行透视划分。这将其带到NDC空间,其中(-1,-1,x)=屏幕左下方,(+ 1,+ 1,x)=屏幕右上方。通过屏幕宽度和屏幕高度进行调整,然后在屏幕空间中获得坐标。

What you need to do is to transform your worldPos vec3 by the viewProjection matrix and then perform the perspective divide. This brings it to NDC space where (-1,-1,x) = bottom left of your screen and (+1,+1,x) = upper right of your screen. Adjust this by your screen width and screen height and you have the coordinate in screen space.

在代码中,它的外观如下:

In code, this is what it looks like:

worldToScreen: function(viewProjectionMatrix, screenWidth, screenHeight){
    var m = viewProjectionMatrix;
    var w = m[3] * this[0] + m[7] * this[1] + m[11] * this[2] + m[15]; // required for perspective divide
    this.transformByMat4(viewProjectionMatrix);
    if (w!==0){ // do perspective divide and NDC -> screen conversion
        var invW = 1.0/w;
        this[0] = (this[0]*invW + 1) / 2 * screenWidth;
        this[1] = (1-this[1]*invW) / 2 * screenHeight; // screen space Y goes from top to bottom
        this[2] *= invW;
    } 
    return this;
}

顺便说一句,这实际上是GPU在引擎盖下所做的工作,减去NDC到屏幕坐标的转换。

Btw this is what essentially what the GPU is doing under the hood to render stuff, minus the NDC to screen coordinate conversion.

检查三种Vector3方法,很可能已在其中实现,或者仅使用上面的代码段。

Check the THREE Vector3 methods, very likely it is implemented there, or just use the code snippet above.

这篇关于使用three.js提取3D点的2D屏幕位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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