简体   繁体   中英

Threejs rotate camera around Y

I am little bit confused with this one :S

I created a code where my camera does his job "halfly". I mean I can rotate the camera on a half-circle with my mousemove events but the aim would be the whole circle :)

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);
    }
  }

Camera movement stops when this.camera.position.z/radius is -1 or 1 :S Could someone help me with this please?:)

If you want to rotate around an axis, why not try using a Quaternion :

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 );

The above will create a rotation (defined as a quaternion ) around the Y-axis and a full rotation will occur every 1000 delta (which could be milliseconds, or pixels, either way) of drag. Heres a sample implementation:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM