Spin Sphere on x-Axis Using Mouse Location in three.js

I have a sphere with an earth texture on it using three.js. The earth rotates horizontally on its own y-axis, but I'm looking to rotate the sphere vertically on its x-axis based on mouse position. When the mouse is at the top of the browser window, the north pole should be visible, and when at the bottom, the south pole. The rotation between the poles should change based on the vertical mouse movement within the window.

How can I achieve this type of rotation?

The following code sets up the three.js scene, however, the rotation math needs refinement:

<html>
    <head>
        <title>Earth Rotation</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

            var geometry   = new THREE.SphereGeometry(1, 100, 100);
            var material  = new THREE.MeshPhongMaterial();
            var earthMesh = new THREE.Mesh(geometry, material);

            material.map = THREE.ImageUtils.loadTexture('images/earth.jpg');

            var light = new THREE.AmbientLight( 0xcccccc );
            scene.add(light);
            scene.add(earthMesh);

            camera.position.z = 1.5;

            document.addEventListener('mousemove', function(event){
                if(event.clientY < window.innerHeight / 2) {
                    earthMesh.rotation.x = ((window.innerHeight / 2) - (event.clientY * .0001));
                } else if(event.clientY > window.innerHeight / 2) {
                    earthMesh.rotation.x = ((window.innerHeight / 2) + (event.clientY * .0001));
                }
            }, false)

            var animate = function () {
                requestAnimationFrame( animate );
                earthMesh.rotation.y -= 0.0005;
                renderer.render( scene, camera );
            };

            animate();
        </script>
    </body>
</html>

Answer №1

Perhaps you could try achieving a similar effect by using THREE.OrbtiControls() with some adjustments.

This is just one way to move the camera around a rotating globe.

r96

var scene = new THREE.Scene();
var camera - new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 10;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerwidth, window.innerheight);
document.body.appendChild(renderer.domElement);

var lm globe = new THREE.Mesh(new THREE.SphereGeometry(4, 32, 16), new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("https://c1.staticflickr.com/3/2521/3884071286_edb50f8137_b.jpg")
}));
scene.add(globe);

window.addEventListener("mousemove", onMouseMove, false);

function onMouseMove(event) {
camera.position.setFromSphericalCoords(10, Math.PI * -event.clientY / window.innerHeight, 0);
camera.lookAt(globe.position);
}

render();

function render() {
requestAnimationFrame(render);
globe.rotation.y -= 0.005;
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/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

Error: The function `this.xhr_.upload.addEventListener` is not supported in Firebase Storage

Having some trouble with file uploads. Small files work fine, but when it comes to larger ones I keep getting this error: this.xhr_.upload.addEventListener is not a function. I'm currently using vue.js along with the firebase 6.1.0 npm package. Th ...

Having trouble retrieving data about my marker through react-leaflet

Hello, I am currently working on accessing information about my marker using React and react-leaflet, which is a library based on Leaflet. I initially tried to utilize useRef, but unfortunately it did not provide the expected results. When attempting to us ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

Instructions for creating a circular image using the Next.js image component in Next.js version 13

Currently, I'm attempting to replicate an image similar to https://i.sstatic.net/EF5Nd.jpg using the latest version of next.js (version 13) with the next.js image component. However, I am encountering a slight issue where the image appears to be takin ...

What is the best way to adjust the padding on the left and right of the Bootstrap navbar logo and menu items?

I am currently facing an issue with the alignment of the logo and menu on my website. They are currently aligned to the far edges of the screen, and I would like them to remain a set percentage distance away from the extremes, rather than an absolute dista ...

What is the best way to set up a function to automatically execute on a specific date and time

I am facing a challenge with my website where users can send themselves messages at a chosen date and time. However, I am unsure how to trigger the message delivery at the specified time. While I am aware of CronJobs, they seem more suitable for recurring ...

Automatically collapse the responsive menu upon selecting a menu item

I have implemented a custom JavaScript code for a basic open/close menu movement on multi-page websites. The code works by closing the menu only when the user clicks the menu symbol. However, I now need to incorporate this code into a one-page website and ...

Converting a database query result into a JavaScript variable: A step-by-step guide

I've been struggling with this problem for a day now and I feel like giving up. My main goal is to export the query result as a string (specifically dataString) so that I can easily import it as a string in my external .js file. module.exports.getKl ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...

The function replace does not exist in t(…)trim

I encountered an error in my code that breaks the functionality when checked using console.log. var map = L.map('map').setView([0, 0], 2); <?php $classesForCountries = []; if (have_posts()) : while (have_posts()) : the_post(); ...

What is causing this code to keep iterating endlessly?

I have a basic jquery script embedded in my HTML code that utilizes the cycle plugin for jQuery. The problem I'm facing is that when I interact with the slideshow using the "next" or "previous" buttons, it continues to loop automatically after that in ...

Utilizing DataLoader in tandem with Mongoose: A comprehensive guide

I am currently working on implementing DataLoader with Mongoose for the following use case: export const PurchaseOrderType = new GraphQLObjectType({ name: "PurchaseOrder", description: "PurchaseOrder", interfaces: () => [NodeInterface], ...

Extracting values from URL query parameters in Vue.js

When dealing with Vue.js callback URLs, I encounter situations where I need to extract a parameter value from the URL. For instance, consider this return URL: http://localhost:8080/#/sucesspage?encryteddata=abdeshfkkilkalidfel&9a I attempted to retrie ...

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

I encountered an issue stating, "The function `req.redirect` is not recognized."

Recently starting out with node development. Encountering the error below: TypeError: req.redirect is not a function at Post.create (/var/www/html/node_blog/index.js:40:7) at /var/www/html/node_blog/node_modules/mongoose/lib/utils.js:276:16 a ...

Design a search page with expandable fields for a user-friendly experience

Initially, my search page displays 12 fields. I would like to add a link labeled "MORE" that will reveal an additional 10 fields, including the original ones. If the user clicks on "HIDE," these extra 10 fields will disappear as well. ...

Conceal the <p> tag if the content inside is either "0" or blank

I'm currently working on a basic calculator project and I've hit a roadblock. I need to hide certain elements based on conditions. The code snippet with explanations is provided below. function calculateArea() { var length = document.getElem ...

What steps can I take to streamline and simplify this tab controller code?

I'm looking to simplify this jQuery code because I feel like there's repetition. As someone new to JavaScript and jQuery, I've created two tabs with their respective containers containing miscellaneous information. My goal is to have each co ...

Showing information in a tree structure using HTML, CSS, and JQuery

Trying to figure out how to present a large amount of data in a tree structure. Each node could have multiple children and parents, requiring a dynamic representation. I've explored various JavaScript libraries like D3 and Raphael, but unfortunately, ...

Making API calls using JavaScript

I'm struggling with understanding how to approach this problem in javascript. Here is the question along with the details. I would appreciate any assistance. QUERY We have a server backend that provides two endpoints: /GetLocalPressReleases and /Get ...