Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To better illustrate the issue, I've included an image below.

https://i.sstatic.net/C2PNW.jpghttps://i.sstatic.net/cyCoI.jpg

In the provided image, the green arrow represents the pipe, while the red line indicates the vector point around which the circular object must rotate on the z-axis to align properly.

My approach involved calculating the angle between the vector point and its center point to determine the required rotation along the z-axis for alignment. While this method works in certain scenarios, it falls short when the object is oriented upside down. Additionally, I am using the last point of the tube as a reference for placement, ensuring that the object remains perpendicular at all times.

rotateobject() {
    //set the object perpendicular to the pipe
      this.hudObj.lookAt(this.previouspoint);
      let zerovector = new THREE.Euler();
      //reset the rotation
      this.hudObj.rotation.copy(zerovector);
      this.hudObj.lookAt(this.previousActualPoint);

      //Line to be able to see if the object is aligned

      var material = new THREE.LineBasicMaterial({
        color: 0x0000ff
      });
      var geometry = new THREE.Geometry();
      geometry.vertices.push(
        new THREE.Vector3( this.previouspoint.x , this.previouspoint.y, this.previouspoint.z),
        new THREE.Vector3( ((this.previouspoint.x) + this.previouspointdata.highSide.x), ((this.previouspoint.y) + this.previouspointdata.highSide.y), ((this.previouspoint.z) + this.previouspointdata.highSide.z) ),
      );   
      var line = new THREE.Line( geometry, material );
      this.scene.add( line );
        /// calculate angle and rotate in z axis
      var angleRadians = Math.atan2(parseFloat(this.previouspointdata.highSide.y.toFixed(1)), parseFloat(this.previouspointdata.highSide.x.toFixed(1)));
      if (angleRadians > '0' && angleRadians < Math.PI / 2) {
        this.hudObj.rotateZ(-(Math.PI / 2 - angleRadians) );
      }//0-90
      else if (angleRadians < Math.PI && angleRadians > Math.PI / 2) {
        this.hudObj.rotateZ((angleRadians - Math.PI / 2) );
      }//90-180
      else if (angleRadians > -Math.PI && angleRadians < -Math.PI / 2) {
        this.hudObj.rotateZ((-Math.PI/2  + angleRadians) );
      }//-180-90
      else if (angleRadians < '0' && angleRadians > -Math.PI / 2) {
        this.hudObj.rotateZ(-(Math.PI / 2 - angleRadians));
      }//-0-90
      else if (angleRadians === '0') {

      } //0
      else if (angleRadians === Math.PI || angleRadians === -Math.PI) {
        this.hudObj.rotateZ(-(Math.PI / 2) );
      }//180
      else {
        if(Math.sign(angleRadians) === -1){
         this.hudObj.rotateZ( Math.PI );
        } 
       }

    }

Your assistance on this matter is greatly appreciated as I find myself stuck. Thank you everyone for your help!

Answer №1

If you're seeking the cartesian coordinates of a point on a sphere, you'll need to have certain information:

You should know the coordinates of the center of the sphere - Xc, Yc, and Zc - as well as the radius of the sphere - r. Additionally, two angles - phi and omega are required. With this information in hand, you can determine the coordinates of that specific point - Xp, Yp, and Zp - using the following equations:

Xp = Xc + (r * cos(omega) * sin(phi))
Yp = Yc + (r * cos(phi))
Zp = Zc + (r * sin(omega) * sin(phi)) 

Take a look at this image for reference.

If you want an object positioned on that point facing the center, you can utilize the lookAt function from THREE.js library:

object.lookAt( Xc, Yc, Zc );

More details on how to use the lookAt function can be found here.

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

What is the best way to verify the existence of an email address?

I'm currently using the jQuery validation plugin and everything is working fine, but I've hit a snag when it comes to checking email addresses. The issue is that the plugin returns either true or false based on whether the email exists or not. Ho ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

Tips for replacing all occurrences of a specific string in HTML while preserving JavaScript attributes

Is there a way to use RegEx to replace part of an HTML document without affecting the root element or other elements like event listeners? Consider this scenario: for (; document.body.innerHTML.indexOf(/ea/) != -1;) { document.body.innerHTML = docu ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

The angular application fails to load the page properly and keeps refreshing itself

I'm currently working on an Angular app that searches for a Github user based on their username and then displays the list of repositories. When a user clicks on a repo name, it should show the open issues and contributors associated with that reposit ...

Showing only the objects that are marked as true in the component (React)

I have implemented two key React components. One of them is VideoGameList.js, it serves as an export of an array containing multiple objects. const VideoGameList = [ { id: 1, title: "Fire Emblem Engage", src: vg01, releaseDate: ...

Is there a way to use a specific keyboard input to alter the characteristics of shapes on my webpage?

Is there a way to change certain attributes of a shape onscreen when a specific key is pressed by the user? For example, can I make it so that pressing "a" changes the color of the shape? I attempted to modify a mouse rollover event to work with the desir ...

Tips for showing error messages in response to exceptions

My function is supposed to display the response text that comes back from ex.responseText. However, every time I attempt it, it returns as "undefined" even though the text is there. onError: function (ex) { $('<div>' + ex._message + &a ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Enhance the functionality of Javascript Promise.then by allowing the argument function to accept an extra parameter

In my code, I am currently utilizing ES6 Promise as shown below: const ctx = {} Promise.resolve() .then(() => doSomethingWith(ctx)) .then((retValue) => doSomethingElseWith(retValue, ctx)) I wish to achieve something like this: const ctx = {} u ...

The color overlay for the class label map segmentation in AMI JS is not appearing as expected

I came across this example in vanilla JavaScript. In my project using Angular 7.3.8 with AMI version 0.32.0 (ThreeJS 0.99.0), I imported everything as an angular provider service. When trying the test examples from the provided link, I noticed that the o ...

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

The compiler throwing an error claiming that the indexOf method is not a valid

Currently, I am working on a simple form that collects user input and aims to validate the email field by checking for the presence of "@" and "." symbols. However, every time I attempt to run it, an error message stating that indexOf is not a function p ...

Combining two HTML tables using jQuery/JavaScript

My table is displayed below: <table id="first" class="merge"> <tr> <td>Mick Jagger</td> <td>30</td> <td>50</td> <td>10</td> </t ...

To address the issue of input values not persisting in a Selenium iframe element, I am implementing a custom JavaScript event to

Attempting to initiate a JavaScript 'change' event on an element within an iframe. The following is the code snippet I have been using: // accessing the iframe window var iframeDoc = document.getElementsByTagName("iframe")[0].contentWin ...

Discover how to retrieve the calculated percentage within CSS with the assistance of jQuery specifically designed for Webkit

I'm currently working on a simple sliding animation. However, the div that slides in is utilizing percentages for its width and right positioning. The issue arises specifically in Webkit browsers. When using jQuery to retrieve the value, it returns t ...

Is there a dependable resource for mastering Protractor along with the Jasmine Framework in Eclipse using JavaScript?

Starting a new role at my organization where I will be testing Angular JS applications. Can anyone recommend a good website for learning PROTRACTOR with JAVASCRIPT using the JASMINE Framework? (Would prefer if it includes guidance on Eclipse IDE) Thank yo ...

Ways to activate javascript following a PHP submission?

It's a bit tricky to explain. function m(val){ var element=document.getElementById('othermethod'); if(val=='others') element.style.display='block'; else element.style.display=&apo ...

Java servlet, Selenium, and JavaScript are a powerful combination of tools that can

I am facing a situation where I need Selenium webdriver to be executed on the client side. On a webpage, I have a form with a Submit button inside it. The action attribute of the form calls a servlet named "servletName". Inside the servlet, the followin ...

Sending data from an AngularJS app to Google App Engine using HTTP post

I'm facing a small issue where I am unable to successfully POST my data (comments) to the GAE datastore using angularjs. Can you please help me identify what's wrong with the following angularjs "post" or html code? ANGULAR: $scope.addComment = ...