Three.js:相机在球体周围飞舞?

时间:2012-06-14 09:18:34

标签: javascript three.js

在Three.js(使用JavaScript / WebGL)中,如何创建一个相对于球体在固定高度,固定前进速度和固定方向上围绕球体飞行的相机,用户只能够左右转向?

想象一架飞机在地球中心的一条看不见的绳子上飞行,飞近地面,总是看到球体的一部分:

enter image description here

(我目前有代码可以将球体旋转到摄像机,看起来它正在飞行 - 左右转向尚未实现 - 但我想在我走得更远之前移动相机/飞机可能更干净,不是球体组。)

谢谢!

2 个答案:

答案 0 :(得分:5)

你的意思是在Ludum Dare 23 game?我发现这比我想象的要复杂一点。不过,这并不困难。

这里我假设您知道相机的纬度和经度及其距球体中心的距离(称为radius),并且想要为相机创建变换矩阵。

仅创建以下对象一次,以避免在游戏循环中创建新对象:

var rotationY = new Matrix4();
var rotationX = new Matrix4();
var translation = new Matrix4();
var matrix = new Matrix4();

然后每次相机移动时,按如下方式创建矩阵:

rotationY.setRotationY(longitude);
rotationX.setRotationX(-latitude);
translation.setTranslation(0, 0, radius);
matrix.multiply(rotationY, rotationX).multiplySelf(translation);

此后只需设置相机矩阵(假设相机是您的相机对象):

// Clear the camera matrix.
// Strangely, Object3D doesn't have a way to just SET the matrix(?)
camera.matrix.identity();
camera.applyMatrix(matrix);

答案 1 :(得分:1)

感谢Martin的回答!我现在用另一种方法运行良好如下(马丁的方法也可能是完美的;还有很多,谢谢Lmg!):

将相机设置为开头球体顶部的直线(即高y值,超出半径,在我的情况下为200);让它看起来有点低:

camera.position.set(0, 210, 0);
camera.lookAt( new THREE.Vector3(0, 190, -50) );

创建一个空组(Object3D)并将相机放入:

camGroup = new THREE.Object3D();
camGroup.add(camera);
scene.add(camGroup);

跟踪与屏幕半部相关的鼠标位置百分比:

var halfWidth = window.innerWidth / 2, halfHeight = window.innerHeight / 2;
app.mouseX = event.pageX - halfWidth;
app.mouseY = event.pageY - halfHeight;
app.mouseXPercent = Math.ceil( (app.mouseX / halfWidth) * 100 );
app.mouseYPercent = Math.ceil( (app.mouseY / halfHeight) * 100 );

在动画循环中,将此百分比应用于旋转,同时自动前进:

camGroup.matrix.rotateY(-app.mouseXPercent * .00025);
camGroup.matrix.rotateX(-.0025);
camGroup.rotation.getRotationFromMatrix(camGroup.matrix);

requestAnimationFrame(animate);
renderer.render(scene, camera);
相关问题