2
注意:以下代碼使用WestLangley的修復更新。projectVector結果不在-1和1之間(three.js)
我試過幾個從3D投影到2D的例子。但是,當我嘗試使用projectVector時,結果不在-1和1之間,所以當我乘以窗口的寬度/高度時,會得到非常大的數字(比我的屏幕分辨率大得多)。希望我的問題很簡單。我使用three.min.js r56,我的內部窗口尺寸是1366x418。
下面的代碼產生3D點(1200,625,100)的投影(x,y):( - 7.874704599380493,-13.403168320655823)。我知道我仍然需要將這個結果乘以一半的窗口高度和寬度,但像素的結果(x,y)遠離屏幕。
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script type="text/javascript" src="three.min.js"></script>
</head>
<body>
<canvas id='container'></canvas>
<script>
/// GLOBAL VARIABLES
var camera, scene, renderer, container, projector;
init();
function toXYCoord (object) {
var vector = projector.projectVector(object.position.clone(), camera);
return vector;
}
/// INIT
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 50, window.innerWidth/window.innerHeight, 0.1, 20000);
scene.add(camera);
camera.position.set(0,-1500,1500);
camera.lookAt(scene.position);
camera.updateMatrixWorld(); ///////////////// THIS IS THE FIX
projector = new THREE.Projector();
// sphere
var sphere = new THREE.Mesh(new THREE.SphereGeometry(200, 32, 16), new THREE.MeshBasicMaterial({ color: 0x000000 }));
sphere.position.set(1200,625,100);
scene.add(sphere);
container = document.getElementById('container');
renderer = new THREE.WebGLRenderer({ canvas: container, antialias:true });
renderer.setSize(window.innerWidth, window.innerHeight);
var testVector = toXYCoord(sphere);
console.log(window.innerWidth + "x" + window.innerHeight);
console.log("Got: (" + testVector.x + "," + testVector.y + ")");
renderer.render(scene, camera);
}
</script>
</body>
</html>
updateMatrixWorld做到了!非常感謝! – kronuus 2013-03-07 15:38:17