【问题标题】:Camera 'twisting' in three.jsThree.js 中的相机“扭曲”
【发布时间】:2021-02-26 17:29:16
【问题描述】:

我正在尝试掌握 three.js 的基础知识,但不明白为什么相机会这样,也不知道如何修复它。

这是我正在使用的一个非常简单的测试设置,只是简单的。

HTML 只是:

<html>
<body>
    <canvas id="canvas" width="1000" height="500"></canvas>
    <script type="module" src="test-camera.js"> </script>
</body>
</html>

test-camera.js 是这样的:

import * as THREE from 'https://unpkg.com/three@0.122.0/build/three.module.js'

async function main() {
    // Scene
    var scene = new THREE.Scene();

    // Camera
    const camera = new THREE.PerspectiveCamera(45, 2, 0.1, 500);
    camera.position.set(0, -20, 2);
    camera.lookAt(0, 0, 0);

    // Plane
    const pGeometry = new THREE.PlaneGeometry(50, 50);
    const pMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide });
    const plane = new THREE.Mesh(pGeometry, pMaterial);
    scene.add(plane);

    // Mesh
    const mGeometry = new THREE.BoxGeometry(10, 10, 10);
    const mMaterial = new THREE.MeshStandardMaterial({
        color: 0xff0000
    });
    var mesh = new THREE.Mesh(mGeometry, mMaterial);
    scene.add(mesh);

    // AmbientLight
    var light = new THREE.AmbientLight(0xffffff);
    scene.add(light);

    // renderer
    const canvas = document.querySelector('#canvas');
    var renderer = new THREE.WebGLRenderer({ canvas });
    renderer.setSize(1000, 500, false);
    renderer.render(scene, camera);
}

main().catch((e) => {
    console.error('error:', e);
});

所以它只是飞机上的一个盒子,有一个摄像头在看它。 (可能会出什么问题??)

我想移动相机以从各个角度查看框 - 因此更改 camera.position.set() 参数“应该”使其工作,只要 camera.lookAt 仍然指向 (0,0, 0)?但是,如果我除了沿负 y 轴(此代码的相机位于 (0,-20,2))之外进行任何操作,相机似乎会扭曲,因此场景会出现旋转。

我知道默认情况下相机开始沿 z 轴看,x 轴从左到右,y 轴从下到上 - 所以我明白为什么相机的这个特定位置会导致场景看起来如我所愿。

但是如何让相机保持飞机“下降”?举个例子,我想将相机移动到 (20,0,2),并且仍然让我的 z 轴在画布中指向上方。

顺便说一句,这与用户移动相机、Orbit 控件等无关 - 我只是想了解如何使代码产生我想要的视图。

我怀疑我遗漏了一些基本的东西......有什么建议吗?

【问题讨论】:

    标签: three.js


    【解决方案1】:

    好的,我终于找到了 camera.up,它当然可以完全解决问题。我不知道为什么在我看过的任何示例代码中都没有看到这一点,但这就是我所追求的。

    为了清楚起见,如果(如上面的示例)我的 x-y 平面是地面,则设置 camera.up = new THREE.Vector3(0,0,1) 可确保 z 轴在渲染时始终朝上。

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多