three.js - 如何将新的相机旋转与之前的变换组合起来?

标签 three.js webgl transformation

我正在尝试在 THREE.js 中实现类似于 FlyControls 的东西,但我无法弄清楚如何正确旋转相机的俯仰角:

http://radiantjs.herokuapp.com/

按 A 或 Z 键“向上看/向下看”。因为该演示中的初始位置已经在偏航轴上旋转,所以俯仰基本上看起来像滚动。

我用于更新相机位置和旋转的代码如下:

/**
 * Updates this View. This is called once per frame.
 * 
 * @param {Number} delta The length of the frame (16 / milliseconds).
 */
update: function(delta) {

        if (this.velocity.length() < 0.15) {
            this.velocity.clear()
        } else {
            this.velocity.multiplyScalar(0.85 * delta)
        }

        if (this.velocity.x || this.velocity.y || this.velocity.z) {
            this.camera.position = this.camera.localToWorld(this.velocity.clone())
            this.camera.position.clamp(-16384, 16384)
        }

        if (this.rotation.length() < 0.15) {
            this.rotation.clear()
        } else {
            this.rotation.multiplyScalar(0.85 * delta)
        }

        if (this.rotation.x || this.rotation.y) {
            var rotation = this.rotation.clone().multiplyScalar(Math.PI / 180)
            this.camera.rotation.add(rotation)
        }
    }

完整的代码也可以在这里找到: https://github.com/jdolan/radiantjs/blob/master/public/scripts/main/view.js#L291

非常感谢任何帮助!

最佳答案

THREE.js IRC channel 中的一位好心用户解释说,完成我想做的事情的最简单方法是将相机包装在一个单独的对象(父级/容器)中。平移和偏航应用于容器,而俯仰应用于相机本身:

this.boom = new THREE.Object3D()
this.boom.position.copy(params.position)
this.boom.up.set(0, 0, 1)
this.boom.lookAt(new THREE.Vector3(0, 1, 0).add(params.position))

this.camera = new THREE.PerspectiveCamera(this.fov, this.aspect, 0.1, 4096)

this.boom.add(this.camera)
this.scene.add(this.boom)

然后在每一帧应用我的变换:

if (this.velocity.length() < 0.15) {
    this.velocity.clear()
} else {
    this.velocity.multiplyScalar(0.85)
}

if (this.velocity.x || this.velocity.y || this.velocity.z) {
    this.boom.translate(3, this.velocity.clone())
    this.boom.position.clamp(-16384, 16384)
}

if (this.avelocity.length() < 0.15) {
    this.avelocity.clear()
} else {
    this.avelocity.multiplyScalar(0.85)
}

if (this.avelocity.x || this.avelocity.y) {
    var rotation = this.avelocity.clone().multiplyScalar(Math.PI / 180)
    this.boom.rotation.y += rotation.y
    this.camera.rotation.x += rotation.x
}

就像魅力一样!请再次注意,偏航应用于 this.boom,而俯仰则应用于 this.camera。这具有相对于吊杆而不是相对于场景旋转相机的效果。

关于three.js - 如何将新的相机旋转与之前的变换组合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350953/

相关文章:

web-config - 使用 web.config 转换有条件地更新元素

math - 任何人都可以为傻瓜推荐一些转换矩阵教程吗?

javascript - 三个 JS 碰撞与 SAT 未对齐的碰撞盒

javascript - Three.jscubeCamera envmap 不工作

javascript - 在 Threejs 中画一条线3

javascript - 三.js程序返回: "Cannot read property ' 0' of undefined"

css - 用 Canvas (three.js)覆盖 Canvas (WebGL)

javascript - 检测是否开启了webgl硬件加速

javascript - Math.random() 未声明的标识符

html - HTML 中的卡片翻转程序无法正确翻转