Rotating a cylinder in a three-dimensional plane using Three.js

I've encountered an issue with linewidth (related to ANGLE on window). To work around this, I am using cylinders between two points in 3D space. So far, I have successfully determined the length of the cylinder based on the distance formula for two points in 3D.

However, I am facing difficulty in determining the angle. My goal is to rotate the cylinder so that the calculated angle connects the two points effectively.

In essence, I am seeking a method to calculate the angle between (x1, y1, z1) and (x2, y2, z2), and apply this angle to modify a cylinder's rotation values (cylinder.rotation.x, cylinder.rotation.y, and cylinder.rotation.z).

Answer №1

If you're looking to align a cylinder using a transformation matrix, here's an example code snippet to help you out:

function createCylinderFromEnds( material, radiusTop, radiusBottom, top, bottom, segmentsWidth, openEnded)
{
    // defaults
    segmentsWidth = (segmentsWidth === undefined) ? 32 : segmentsWidth;
    openEnded = (openEnded === undefined) ? false : openEnded;

    // Dummy settings, replace with your own code:
    var length = 100;
    var cylAxis = new THREE.Vector3(100,100,-100);
    var center = new THREE.Vector3(-100,100,100);
    
    var cylGeom = new THREE.CylinderGeometry( radiusTop, radiusBottom, length, segmentsWidth, 1, openEnded );
    var cyl = new THREE.Mesh( cylGeom, material );

    // apply transformation to align with given axis and move to center
    makeLengthAngleAxisTransform( cyl, cylAxis, center );

    return cyl;
}

// Function to transform cylinder to align with given axis and move to center
function makeLengthAngleAxisTransform( cyl, cylAxis, center )
{
    cyl.matrixAutoUpdate = false;

    // Translate first before rotating
    cyl.matrix.makeTranslation( center.x, center.y, center.z );

    var yAxis = new THREE.Vector3(0,1,0);
    cylAxis.normalize();
    var rotationAxis = new THREE.Vector3();
    rotationAxis.crossVectors( cylAxis, yAxis );
    if ( rotationAxis.length() < 0.000001 )
    {
        rotationAxis.set( 1, 0, 0 );
    }
    rotationAxis.normalize();

    var theta = -Math.acos( cylAxis.dot( yAxis ) );
    var rotMatrix = new THREE.Matrix4();
    rotMatrix.makeRotationAxis( rotationAxis, theta );
    cyl.matrix.multiply( rotMatrix );
}

This code snippet is part of the Chapter 5: Matrices in the free Interactive 3D Graphics course available here. You can find the full working sample on GitHub.

If you are new to transformations, I recommend starting with Chapter 4 before diving into this.

Another tip is to use Matrix4's lookAt() method for rotation and adjusting the translation pivot point before applying the matrix to the cylinder.

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 the Firefox API to determine if a tab is currently active

I remember hearing about a feature that was introduced in some recent versions of Firefox allowing developers to check if a tab is active or not using JavaScript. However, I am having trouble finding more information about it online. Can you share the li ...

There has been an issue with the server: Unable to find the image URL in the source (undefined)

When de-structuring the image array from the product and using log to verify if it's getting correctly. Despite confirming that, an error still occurs while passing the image to the urlFor function which is in client.js file. [slug].js import React, ...

code snippet for callback function in javascript

Recently, I've been working on a project with angularjs and phonegap and stumbled upon this interesting code snippet. While I have a basic understanding of what it does, the inner workings are still a bit unclear to me. Since I'm still getting fa ...

Stripe: Either a source or customer must be provided

I've been working on incorporating Stripe into my online shopping cart project, but I've hit a roadblock. Whenever I try to submit the checkout form, I keep encountering the error message: "Must provide source or customer." I suspect there might ...

Steps for creating a TypeScript class that can implement an interface

As a beginner in TypeScript, I am looking for help with the following code snippet: async function sleep(ms: number) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), ms) }) } async function randomDelay() { ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

Can data be transferred from a sub-component to a main component in React?

As I develop a food ordering web app, I decided to split the ordering page into components. However, I am facing an obstacle in passing a variable to the parent page. Specifically, I aim to gather item.Price and item.specBurgerType and transmit them to the ...

Discovering the exact distance between a 'li' and a 'div' element

Currently, I am in the process of converting HTML to JSON. Here is an example of the HTML I am working with: <div class="treeprofit" id="divTreeViewIncomeDetails" style="height: auto;"> <li><span class="fa fa-folder-open highlight" ...

Verifying changes using Cypress transformations

I'm brand new to using Cypress and I am currently attempting to verify that one of my elements contains a specific style. The element in question looks like this: <div class="myElement" style="transform: translate(0%, 0px); "></div> Her ...

What methods do languages use to manage the side effects caused by compound operators?

Let's consider a scenario like this: int a = (--t)*(t-2); int b = (t/=a)+t; While in C and C++, this leads to undefined behavior, as explained in this article: Undefined behavior and sequence points But how is this situation handled in: JavaScrip ...

How can I obtain the MAC address of a tablet (iPad or Android)?

Synopsis: My project involves creating a HTML5 web app designed for tablets like iPad or Droid to log in to a server and perform various tasks. The client has requested a way to retrieve the device's MAC address during the login process. Most solution ...

What is the best method to determine the time difference between two timestamps using JavaScript?

Could you kindly show me how to calculate the difference between two times using JavaScript? I have attempted to find a solution, but I am encountering errors. Here is the code snippet from my fiddle: Visit my jsFiddle var currentTime = new ...

"Enhance interactivity in R with Plotly by creating clickable URLs for faceted

I am working with a ggplot2 plot that passes to plotly and then outputs to html using Rmarkdown. I am attempting to implement a JS function that opens the underlying URL when clicking on the points. Despite my efforts, the faceting seems to alter the point ...

What is the best way to remove comments in javascript?

My collection of files all have similar comments at the beginning, such as: /* * @title Add profile picture upload feature * @overview Allow users to upload a profile picture to their account. * @gallery true * @category user management * * This rul ...

Transform the Asp.net JavaScript jsgantt-improved Gantt chart to be compatible with Blazor

Struggling to implement a Gantt chart in Blazor with razor pages after finding a nice one for Asp.net. Any tips on how to proceed? I've already added jsgantt.js and jsgantt.css to wwwroot and included references in index.html. But now, how do I go a ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

Once the email has been successfully sent and the modal has been called, the submit button should be deactivated permanently

Hello everyone, I need some help with a programming challenge I'm facing. I am trying to permanently disable the 'Approve' button, which sends an email using PHP and triggers a modal when clicked. I've attempted to use local storage to ...

Details regarding the enthusiastic execution of Promise callbacks

Is there a specific specification or implementation detail that dictates how quickly the callbacks of a promise are evaluated? For example, if I have: var promise = new Promise((resolve) => { resolve() }); console.log(promise); // there is no p ...

Is there a way to trigger an error message if a response is not received within one minute in Node.js?

In my current setup, I am using Node version 6.15. Within this code snippet, there is a promise method that returns a response after calling another function. myFunction: (params) = { return innerFunction(params) .then((resp) => { return resp ...