Writing a JavaScript equation using three.js to orbit an object in a circular path around a central y-axis in a 3D space

Currently, I am playing around with threeJS and have managed to position the camera to look at the origin point of a scene (0,0,0). My goal is to rotate the camera in a circular path around the y axis at a specific distance (radius) while keeping its focus on the origin. However, I am unsure about how to formulate the equation for this movement. Currently, I am simply rotating the object itself, but I would prefer to rotate the camera instead. Below is the code snippet I am using to move the mesh:

function checkRotation(){
    if (keyboard.pressed("left")){
        mesh.rotation.y += .05;
    }

    if (keyboard.pressed("right")){
        mesh.rotation.y -= .05;
    }
}

Here is an example of how I envision moving the camera:

camera.position.x = ??? (an equation for adjusting its x position) camera.position.z = ??? (an equation for adjusting its z position) camera.lookAt(mesh.position);

Any assistance or guidance on this matter would be greatly appreciated. Thank you!

Answer №1

If you want to manually adjust the camera position, you can do so by following these steps:

// Define the rotation angle as theta
var x = camera.position.x;
var z = camera.position.z;

camera.position.x = x * Math.cos(theta) + z * Math.sin(theta);
camera.position.z = z * Math.cos(theta) - x * Math.sin(theta);
camera.lookAt(mesh.position); // or camera.lookAt(0, 0, 0);

Refer to http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions for the matrix representation of rotating around x, y, and z axes.

You may also consider modifying TrackballControls to function with keyboard inputs instead of mouse.

Check out the default Trackball behavior:

Please note that I have not yet tested this code as I am currently at work.

Answer №2

Although this response may be tardy, those interested might benefit from exploring the OrbitControls feature included in the examples/js/controls folder of Three.js library. With autoRotate enabled, the mathematical calculations are handled effortlessly.

var controls = new THREE.OrbitControls(camera);
controls.autoRotate = true;
controls.autoRotateSpeed = [specify desired speed]

camera.lookAt(new THREE.Vector3(0,0,0));

In your update function called by requestAnimationFrame...

controls.update();

If manual camera control isn't desired, consider disabling it or extracting necessary code snippets accordingly.

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

Using (javascript:) within Href attributes

Recently, I've noticed some people including "javascript:" in the href attribute of an a tag. My question is: what is the purpose of this? Does it guarantee that clicking on the a tag directs the function of the click to JavaScript for handling, rathe ...

Having trouble getting three.js animation to load?

I'm having some trouble getting a GLTF animation of a bird to work in my 3js app. When I console log the object, it shows that the animation is stored in an array index of 0. I also tried adding rotation to test, but that didn't work either. Any ...

Using JS/AJAX to update a section of a webpage when a button is clicked

Currently, I am working on developing a generator that will display a random line from a .txt file. Everything is going smoothly so far, but I have encountered an issue - I need a specific part of the page to refresh and display a new random line when a ...

What is the method to reverse this calculation?

Currently, I have been using this formula to increase the alpha value of a view as it moves along. If the distance travelled is represented by deltaX and mViewWidth is the object's width being moved, how can I modify the calculation to decrease the al ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Steps for permanently closing dismissible alerts in Bootstrap 4

On my MediaWiki site, my goal is to display a bootstrap 4 alert for new visitors on specific pages, and have it stay permanently dismissed after it is closed. The alert will be transcluded to multiple pages, but once dismissed, it should not reappear on an ...

What is the process for refreshing the component content in Angular 2?

There was a moment during execution when my URL had the following appearance: http://localhost:4200/personal/51c50594-a95c-4a18-ac7b-b0521d67af96 I desire to visit a page with a different GUID and different content. http://localhost:4200/personal/{other ...

Using asynchronous method calls to create arrays in ES6

In my current task, I am working on completing the following method: collectAllResults: function (callback) { this.getTotalCount((count) => { // the count typically is 5 let results = [] for (var i = 0; i < count; i++) { th ...

React, connecting form inputs

I've encountered an issue with binding the value of an input in one of my app's components. Strangely, I had no trouble doing this in another component, but now I'm only able to get the first letter of the input instead of the entire text. ...

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Where is the source of this ever-changing image?

Recently, I decided to dive into the world of jQuery and experiment with a plugin carousel. However, I must admit it is all a bit overwhelming for me at the moment. Currently, I have the plugin installed and I am struggling to get rid of the bottom scroll ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

How can I make an AJAX request in Rails 3 to retrieve an HTML page?

I am experimenting with using Rails to display an .html.erb template via an ajax request under specific conditions. By default, I am consistently receiving the .js.erb file when making an ajax request. Without delving into the reasons behind this choice, ...

"Tricks to prompt the browser to refresh and load up-to-date content

Currently experiencing issues with my web browser (both on my laptop and smartphone). I am working on a website page (HTML, javascript) and have observed that my browser keeps retrieving cached information instead of loading the page each time, preventing ...

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

Is there a way to identify a visitor's country and automatically direct them to a relevant website?

Despite reading multiple answers, I am still unsure how to redirect my website's visitors based on their country. I have a basic understanding of HTML and JavaScript. Can someone kindly provide me with the code for this task? ...

Saving props in React-select

I'm currently utilizing react-select to enable multiple selection on my UI. However, I need to extract the props from react-select since I will be sending the selected values to the backend. My query is how can I store the state values in an array for ...

Unable to invoke any fineUploader functions within a callback function

My autoUpload is currently set to false because I prefer uploading the images manually to my backend. To achieve this, I need the file object first. In the onSubmitted event callbacks, I am attempting to pass the image's ID to the getFile method to re ...