How to get the Vector3 of a point from the viewport perspective in three.js?

删除回忆录丶 提交于 2021-01-28 02:38:45

问题


I need to create 2 THREE.Vector3 points. from the browser viewport perspective.

  • The starting point is the top right corner of the browser viewport, far from the screen
  • The ending point is the centre (both horizontal centre and verticle centre) of the browser viewport, close to the screen.

The problem is, how could I convert the web coordinate to the three.js coordinate so I can start making this cubic bezier curve3?

Google Fu is not working for me this time... what am I missing here? Thanks


回答1:


What you're looking for is Vector3.unproject(). This mechanism converts screen-space coordinates in the [-1, 1] range, to a 3D position by "unprojecting" it from the camera.

The screen-space coordinates, also known as normalized device coordinates (NDC), are as follows:

x = -1  // left side of the screen
x = 1   // right side of the screen
y = -1  // bottom
y = 1   // top
z = -1  // far plane
z = 1   // near plane

So if you want the right-top-far corner to center-center-near, follow the table above:

var camera = new THREE.PerspectiveCamera(/* ... */);

// Start in NDC space
var cornerVec = new THREE.Vector3(1, 1, -1);
var middleVec = new THREE.Vector3(0, 0, 1);

// Convert to 3D space
cornerVec.unproject(camera);
middleVec.unproject(camera);

console.log(cornerVec);
console.log(middleVec);

You can read more about Vector3.unproject() in the docs. It's called "unproject" because it does the opposite of "project".



来源:https://stackoverflow.com/questions/65820310/how-to-get-the-vector3-of-a-point-from-the-viewport-perspective-in-three-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!