gpt4 book ai didi

javascript - Threejs 围绕 Y 旋转相机

转载 作者:行者123 更新时间:2023-11-28 14:35:04 25 4
gpt4 key购买 nike

我对这个有点困惑:S

我创建了一个代码,让我的相机“半”完成他的工作。我的意思是我可以通过鼠标移动事件将相机旋转半圆,但目标是整个圆:)

onRotateCamera(event){
if(this.cameraDragged){
let radius:number = Math.round(Math.sqrt(this.camera.position.x * this.camera.position.x + this.camera.position.z * this.camera.position.z)*1000)/1000;
let delta:number = (this.cameraDragged.clientX - event.clientX) / 1000;
let angle:number = Math.round(Math.asin(this.camera.position.z/radius)*1000)/1000;

angle += delta;
this.camera.position.x = Math.round(radius * Math.cos( angle )*1000)/1000;
this.camera.position.z = Math.round(radius * Math.sin( angle )*1000)/1000;
this.camera.lookAt(this.scene.position);
}
}

当 this.camera.position.z/radius 为 -1 或 1 时,相机移动停止:S有人可以帮我解决这个问题吗?:)

最佳答案

如果您想绕轴旋转,为什么不尝试使用四元数:

camera.position.applyQuaternion( new THREE.Quaternion().setFromAxisAngle
new THREE.Vector3( 0, 1, 0 ), // The positive y-axis
RADIAN / 1000 * delta // The amount of rotation to apply this time
));
camera.lookAt( scene.position );

以上将创建围绕 Y 轴的旋转(定义为四元数),并且每 1000 个delta 就会发生一次完整旋转(可以是毫秒,也可以是像素)的拖动。这是一个示例实现:

var renderer = new THREE.WebGLRenderer;
var scene = new THREE.Scene;
var camera = new THREE.PerspectiveCamera;
var last = false;
var quaternion = new THREE.Quaternion;
var axis = new THREE.Vector3( 0, 1, 0 );

renderer.domElement.addEventListener( 'mousedown', event => {

last = new THREE.Vector2( event.clientX, event.clientY );

});

renderer.domElement.addEventListener( 'mousemove', event => {

if( last ){

let delta = event.clientX - last.x;

camera.position.applyQuaternion( quaternion.setFromAxisAngle(
axis, Math.PI * 2 * (delta / innerWidth)
));
camera.lookAt( scene.position );

last.set( event.clientX, event.clientY );

}

renderer.render( scene, camera );

});

renderer.domElement.addEventListener( 'mouseup', event => {

last = false;

});

scene.add( new THREE.Mesh( new THREE.BoxGeometry, new THREE.MeshBasicMaterial ) );
scene.add( new THREE.AxesHelper );

renderer.setSize( 512, 512 );

camera.position.set( 0, 0, 5 );

renderer.render( scene, camera );

document.body.appendChild( renderer.domElement );
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>

关于javascript - Threejs 围绕 Y 旋转相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com