Spin the Three.js camera in a circular motion along the Y-axis

I'm feeling a bit puzzled about this one :S

I've written a code that allows my camera to rotate only halfway. I can move the camera along half of a circle using mousemove events, but I actually want it to be able to complete a full rotation :)

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

The camera movement stops when this.camera.position.z/radius is either -1 or 1 :S Could someone assist me with fixing this issue? Thank you! :)

Answer №1

To achieve rotation around an axis, consider utilizing a Quaternion:

camera.position.applyQuaternion( new THREE.Quaternion().setFromAxisAngle
    new THREE.Vector3( 0, 1, 0 ), // Y-axis direction
    RADIAN / 1000 * delta // Amount of rotation per drag
));
camera.lookAt( scene.position );

The code snippet above will generate a rotation (represented by a quaternion) around the Y-axis with a full rotation occurring every 1000 delta units. Below is an example 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to integrate Three.js into Angular 14 while managing dependencies

I'm currently working on developing a web app using angular cli and incorporating three.js for enhanced product interaction. Despite watching numerous tutorials, I've been unable to successfully integrate three js into angular 14. It seems to wor ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

The pie chart fails to fully display

Check out the repro example I made here. The legend is displaying properly, but the graph is not showing up. What could be causing this unexpected issue? ...

How can we process the incoming data that is in a JSON format?

I'm in the process of creating a Zap that collects customer feedback through Unbird and delivers a coherent Slack message that can be easily understood by anyone within my organization. When importing customer feedback data from Unbird into Zapier, i ...

What sets apart the implementation from the Three.js demo?

Attempting to replicate the provided example using react-three-fiber. Example link: https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_sphere.html (currently only implemented the init method, no animation) Here is my code: const Sphere = ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Surprising outcome from the glob-fs glob.readdirSync function

Below is some nodejs code that I am working with. The client initially calls /api/demosounds and then calls /api/testsounds. var glob = require('glob-fs')({ gitignore: true }); app.get('/api/demosounds',function(req,res){ var d ...

`Is there a way to choose several radio buttons with varying names using just one label?`

Is there a way to choose multiple radio buttons with different names using just one label? Here's an example of what I'm attempting to accomplish... <input id="1A" type="radio" name="first" value="A">firstA<br> <input id="1B" typ ...

Changing the templateUrl of a directive on the fly using the controller

How can I dynamically pass the templateUrl for the app_modal directive from the "ServerController" controller to allow for different templates for different modals? I have included the URL as an attribute in the "app-modal" tag used in the server_group.htm ...

Leverage the power of React in tandem with Express

My web site is being created using the Express framework on NodeJS (hosted on Heroku) and I'm utilizing the React framework to build my components. In my project, I have multiple HTML files containing div elements along with React components that can ...

Simple steps to convert Redux state to Redux Persist with the help of 'combineReducers' function

I'm facing a challenge trying to implement Redux-Persist with my Redux state, particularly because I am using combineReducers. Here is the structure of my store: import { createStore, combineReducers } from 'redux' import { usersReducer } fr ...

Error: AJAX response shows as NaN, indicating that the requested resource was not found

Attempting to create a search engine using AJAX. When typing in the search box, nothing happens. After inspecting the element and opening the console, an error message is displayed: script.js:19 GET http://localhost/var/www/html/pendaftaran-siswa/NaN 404 ( ...

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Align Headers to the Top Center in React Material-UI Datagrid

Is there a way to align the wrapped headers at the top-center using sx? I've tried the following code: const datagridSx = { '& .MuiDataGrid-columnHeaders': { height: 'unset !important', maxHeight: '168p ...

troubleshooting Axios errors in React applications

User/Project.js: import React, { useState, useEffect } from "react"; import Axios from "axios"; const Project = () => { const [projectName, setprojectName] = useState(""); const [projectDescription, setprojectDescriptio ...

Navigating through an array of latitude and longitude pairs during an AJAX request

Just starting out with PHP/AJAX and I could use some guidance. Currently, I have a leaflet map where I'm attempting to link two AJAX calls together. The initial AJAX call retrieves data based on a selected country ISO code. Subsequently, I've ut ...

Error: Sorry, there was an issue with the code (React)

I'm attempting to build a React project without Node, and I'm trying to call a JS file from an HTML file. This is just a simple example for learning purposes. However, I keep encountering the Uncaught SyntaxError: Unexpected token '<&apos ...

Top method for saving information on page for Ajax calls

On my dynamically generated page, there is an array of data produced by php that I want to utilize for an ajax request. However, I am unsure of the best method to store this data on the page as it is not sensitive and does not involve a form. Currently, I ...

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...