Three.js 硬核代码片段(长期更新)
1 获取相机朝向(方向向量)
const forward = new THREE.Vector3();
forward.set(0, 0, -1).applyQuaternion(camera.quaternion);
2 坐标系变换
function world2screen(v, camera) {
var vector = v.clone().project(camera);
vector.x = Math.round(((vector.x + 1) / 2) * window.innerWidth);
vector.y = Math.round((-(vector.y - 1) / 2) * window.innerHeight);
return {
x: vector.x,
y: vector.y
};
}
function screen2ndc(screenPos, screenWidth, screenHeight) {
const ndc = {
x: (screenPos.x / screenWidth) * 2 - 1,
y: -(screenPos.y / screenHeight) * 2 + 1,
z: 0
};
return ndc;
}
function ndc2screen(ndcPos, screenWidth, screenHeight) {
const screen = {
x: ((ndcPos.x + 1) / 2) * screenWidth,
y: (-(ndcPos.y - 1) / 2) * screenHeight,
z: 0
};
return screen;
}
function ndc2world(worldPos = {x: 0, y: 0, z: 0}, ndcPos = {x: 0, y: 0, z: 0}, camera) {
let worldVec4 = new Vector4(worldPos.x, worldPos.y, worldPos.z, 1.0);
let ndcVec4 = new Vector4(ndcPos.x, ndcPos.y, ndcPos.z, 1.0);
worldVec4.applyMatrix4(camera.projectionMatrix);
ndcVec4.multiplyScalar(worldVec4.w);
ndcVec4.applyMatrix4(camera.projectionMatrixInverse);
return {
x: ndcVec4.x,
y: ndcVec4.y,
z: ndcVec4.z
};
}