Rotating a Three.js Object in 3D

Hey there! I've encountered an unusual issue in THREE JS(r71) / THREEx (THREEx.LaserBeam). The problem lies with the rotation of Object 3D.

I'm converting latitude and longitude points into phi and theta as follows: (Using different variables for the values 50 and -51)

var phi = (90 - 50) * Math.PI / 180;
var theta = (-51) * Math.PI / 180;

Following this, I place a sphere at the calculated coordinates using this code:

var geometry = new THREE.SphereGeometry( 0.005, 15, 15 );
var material = new THREE.MeshBasicMaterial( {color: 0x0000ff} );
var sphere = new THREE.Mesh( geometry, material );

scene.add( sphere );

sphere.position.x = 0.5 * Math.sin(phi) * Math.cos(theta);
sphere.position.y = 0.5 * Math.cos(phi);
sphere.position.z = 0.5 * Math.sin(phi) * Math.sin(theta);

Next, I align my ray to the same position using the following code:

laserBeam.rotation.y = -theta
laserBeam.rotation.z = phi

The laserBeam is essentially functioning as a "line" within an Object3D. Despite being positioned at (0,0), I am puzzled why it doesn't intersect with the sphere (Refer to screenshot).

Any insights or suggestions?

---EDIT--- Here's an example using a simple line instead:

var phi = (90 - 50) * Math.PI / 180;
var theta = (-51) * Math.PI / 180;
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(0, 0, 0));
geometry.vertices.push(new THREE.Vector3(1 * Math.sin(phi) * Math.cos(theta), 1* Math.cos(phi), 1 * Math.sin(phi) * Math.sin(theta)));
var material = new THREE.LineBasicMaterial({
                                    color: 0x0000ff
                                });
var line = new THREE.Line(geometry, material);
containerLine   = new THREE.Object3D();
containerLine.add( line );
scene.add(containerLine);

Answer №1

You made an error in your calculation of the small radius and y-coordinates:

var rm = R * Math.cos(phi); // should be `R * Math.sin(phi)`
sphere.position.x = rm * Math.cos(theta);
sphere.position.y = R * Math.sin(phi); // should be `R * Math.cos(phi)`
sphere.position.z = rm * Math.sin(theta);

http://jsfiddle.net/sxen2kLd/

Answer №2

Finally, after a long day.... I'm too exhausted to fully comprehend right now, but here it is

function convertLatLngToVector(lat, lng, radius, height) {
                    var phi = (lat)*Math.PI/180;
                    var theta = (lng-180)*Math.PI/180;

                    var x = -(radius+height) * Math.cos(phi) * Math.cos(theta);
                    var y = (radius+height) * Math.sin(phi);
                    var z = (radius+height) * Math.cos(phi) * Math.sin(theta);

                    return new THREE.Vector3(x,y,z);
                }

var positionHelper = convertLatLngToVector(51.227821, 51.3865431, 0.5, 0);
    var geometry = new THREE.SphereGeometry( 0.005, 15, 15 );
    var material = new THREE.MeshBasicMaterial( {color: 0x0000ff} );
    var sphere = new THREE.Mesh( geometry, material );

    scene.add( sphere );

    sphere.position.x = positionHelper.x
    sphere.position.y = positionHelper.y
    sphere.position.z = positionHelper.z
    -----------------------------------------------------
    var rotationHelper = convertLatLngToVector(51.227821, 51.3865431, 0.5, 0);
    function rotateObjectAroundAxis(object, axis, radians) {
      rotWorldMatrix = new THREE.Matrix4();
      rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
      rotWorldMatrix.multiply(object.matrix);
      object.matrix = rotWorldMatrix;
      //object.rotation.setEulerFromRotationMatrix(object.matrix);
      object.rotation.setFromRotationMatrix(object.matrix);
    }


    laserBeam.useQuaternion  = true;

    var origVec = new THREE.Vector3(1, 0, 0);
    var targetVec = rotationHelper;
    targetVec.normalize();
    var rotateQuaternion = new THREE.Quaternion();
    var axis = new THREE.Vector3(0, 0, 0); 
    var angle = Math.acos(origVec.dot(targetVec));
    axis.cross(origVec, targetVec);
    axis.normalize();

    rotateObjectAroundAxis(laserBeam, axis, angle);

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 to create temporary drawings on a webpage that automatically erase themselves

I am curious about how to achieve a scribble effect that self-erases, similar to what is seen on this website: Example: Thank you! I have come across some similar scripts, but I am struggling to understand how to make the scribble disappear after a few ...

Invoking Redux actions within a React component

I'm attempting to send a variable to a Redux action, however, it seems that the action is receiving undefined. What could be causing this issue? index.js - location of action invocation import React from 'react' import { connect } from &ap ...

Ways to reach out to an item on a page that is loaded dynamically

On my webpage firstpagemidle.php, I have a div with the following code: DIV id="news" data-pageNum_rsnews="1" data-totalRows_rsnews="9" class="new"> To load this page on another page, I use the following code: $( ...

Having trouble persisting and displaying information in MongoDB with Mongoose

app.post('/contact', (req, res)=> { var myData = new Contact(req.body); myData.save().then(()=>{ res.send("Item has been saved"); }).catch(()=>{ res.send('Item was not saved due to some error'); ...

Implementing the Disabled Attribute on a Dynamically Generated Button Using React

My QWERTY keyboard is dynamically rendered through a component as Bootstrap buttons using bootstrap-react. Each button does not have an ID to avoid relying on IDs in React. When a letter button is clicked, it triggers an onClick event passed as props back ...

Encountering a situation where an empty object is received while attempting to send a

While using Postman to make a request to the API I created for Social Media Application that involves following and followers functionality, I noticed that I am receiving an empty object: {}. However, upon inspection, everything seems to be correct on my e ...

The nativeElement in Angular is not defined

I need help creating a PDF from HTML content within an Angular application. Check out my main component: Main Component HTML: <div class="container-fluid"> <!-- ... other HTML content ... --> <div class="table-respon ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Implement the switch case statement within a node.js application

When it comes to implementing a switch case for registration flow, there are various options available. For instance, you can have the user sign up using their email, phone number, and password; or they can opt for signing in with Google, Facebook, and man ...

Can Fields Be Concealed Based on the User's Choice?

Can options be dynamically hidden in a select field based on user input using Javascript or jQuery? I am working on a complex and lengthy form and I'm trying to minimize the number of HTML elements to avoid confusion with conditional logic. The user ...

Failure of AngularJS $http GET request

function ContactDetails($scope, $http) { $http({ method: 'GET', url: 'myurl/?', params: { 'company': '1571', 'secret': 'complex15', 'mode': 'contactdetai ...

Bootstrap modal's offset returning blank value

One way to navigate to a specific element within a Bootstrap modal is by checking the offset of that particular element. If there are multiple divs within the modal, each with its own unique id (#row-1, #row-2, etc.), you can open the modal and input the f ...

What is the best way to clear and refresh specific query parameters from the current URL?

For instance, my current URL looks like this: http://domain.com/category/health-beauty/?session={%22session_key%22%3A%22df1eca3f79e122bd915651e5-1325102496%22%2C%22uid%22%3A%221325102496%22%2C%22expires%22%3A0%2C%22secret%22%3A%229eb858d1fc7dda2b37be91228 ...

Guide on Importing All Functions from a Custom Javascript File

As a beginner in learning Angular, I am faced with the task of converting a template into Angular. However, I am struggling to find a solution for importing all functions from a custom js file into my .component.ts file at once. I have already attempted t ...

javascript function returns an array

My behaviors are not returning properly function listBehaviors() { var behaviors = getBehaviors(); console.log("Creating behavior list"); console.log(behaviors); $.each(behaviors, function (index, value) { if (value.indexO ...

Utilizing Vue.js to convert blobs into objects or strings and assign them to application variables

I am currently working on a Vue app and have the following setup: data: function() { return { modules: [], ... Along with the following method: methods: { submitted: function(){ ... axios({method: 'get', ...

What are the steps to integrate the aws-iot-device-sdk NPM module with Angular 11? I am encountering errors related to fs, path, and tls during the build process

I manage a browser-based Angular application that was previously on version 5.6. This app consists of two components that subscribe to an IOT topic and listen for updates without publishing. The task at hand is to upgrade to Angular 11.0.3, which I have c ...

Using Rails to render a partial with a JSON object

In my rails app, there is a javascript callback that runs after a post is created. This callback polls a processing endpoint to check if an image has finished processing and then updates the view accordingly: create.js.erb create callback // initiating t ...

Encountering a CSS problem while attempting to design a section featuring a background image

On this page, I have the login bar on the right and the footer at the bottom. I want a div to sit in the area currently occupied by the background image and fill it with the full background image. Currently, everything is wrapped in a wrapper and the back ...

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...