Using Three.js to Spin Cylinder Towards a Vector3 Destination

I've attempted a thorough search, but unfortunately, I haven't come across any solutions that address my issue:

I have a vector and a CylinderGeometry Mesh. My goal is to make the cylinder face the direction indicated by the vector. The input parameters include a position (c) and a direction (m) similar to a line equation (y = mx + c):

function draw (m,c, _color) {
  //... create the geometry and mesh
  // set the position
  line.position.x = c.x;
  line.position.y = c.y;
  line.position.z = c.z;

  // I attempted something along these lines:
  line.lookAt(c.add(m));

  //.. then add to scene
}

However, it seems like the direction is opposite of what I intend to achieve.

Moreover, I experimented with translation techniques:

geometry.applyMatrix( new THREE.Matrix4().makeTranslation(0, length/2, 0));

I also tried manually calculating the rotation using

line.rotation.x = direction.angleTo(vec3(1,0,0))* 180 / Math.PI;
. Unfortunately, none of these methods provided the desired outcome.

Answer №1

Here's a solution that has worked well for me:

// Creating a cylinder geometry with specified dimensions and orientation
  var geometry = new THREE.CylinderGeometry( 0.6, 0.6, distance, 8, 1, true );
  // Adjusting the position of the geometry to align one end with the origin
  geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, distance / 2, 0 ) );
  // Rotating the geometry in the correct direction for proper lookAt functionality
  geometry.applyMatrix( new THREE.Matrix4().makeRotationX( THREE.Math.degToRad( 90 ) ) );
  // Generating a mesh using the defined geometry and material
  var mesh = new THREE.Mesh( geometry, material );
  // Setting the position of the mesh where desired
  mesh.position.copy( from.sceneObject.position );
  // Directing the mesh to face a specific target location
  mesh.lookAt( to.sceneObject.position );

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

Is there a way to automatically populate an AngularJS input field?

Attempting to automate filling out a website using JavaScript. The script below: document.getElementsByClassName('form-control')[1].value = "MYNAME"; The input text changes, but upon clicking the submit button it displays as empty. Any as ...

From Vanilla Javascript to ES6 Spread Operator

I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax. While it is straightforward to apply t ...

I am having trouble getting the graph to display using PHP and MySQL on Fusion Charts

I am looking to create a line graph based on data from my database. This is my first time working with Fusion Charts, so I followed the instructions in their documentation for dynamic charts. Here is the code from my PHP page: <?php include("Includes/F ...

Is it possible to use D3 for DOM manipulation instead of jQuery?

After experimenting with d3 recently, I noticed some similarities with jquery. Is it feasible to substitute d3 for jquery in terms of general dom management? This isn't a comparison question per se, but I'd appreciate insights on when it might b ...

If the option is 'Gel', use an if statement to console log

I'm trying to console.log the option from the data() function that is equal to 'Gel'. I attempted to use an if statement, but it doesn't seem to be working. Anyone have any ideas on how to make this work? data(){ return { ...

Loop through the input template using ng-repeat with various data types

I have been working on developing a user interface for adding and modifying information in a database. To manage the database, I am utilizing breeze, displaying data using angular grid, and incorporating a ui-bootstrap modal dialog for user interaction. ...

Determine whether a specific text is contained within a given string

Can someone help me determine if a specific text is included in a string? For example, I have a string str = "car, bicycle, bus" and another string str2 = "car" I need to verify if str2 exists within str. I'm new to JavaScript so I appreciate you ...

Navigating the route on express.js using two strings can be done by matching them effectively

I have a single route function that should match two different paths. The goal is to create profile pages for team members on a website, which can be accessed at www.domain.com/name. However, some team members prefer to use nicknames instead of their actua ...

Is there a way to extract data within xml tags with attributes using JavaScript/ Ionic without relying on DOM or ActiveXObject?

I am trying to extract specific information located between two tags, specifically <wsse:BinarySecurityToken> Here is an example: <wsse:BinarySecurityToken att1="abc" att2="cd3" att3="adfa">This is the text I am trying to extract!!!</wsse ...

Implementing Multiple UV Maps for Enhanced Texture Rendering in a threejs Model

Seeking advice and opinions on a complex matter: I have a 3D model of a men's dress shirt in Collada format, accurately sized with a 16-inch neck and 34-inch sleeves. I also have three polka-dot fabrics (perhaps I have a penchant for polka dots). Here ...

The process of AngularJS one-time binding is triggered twice

Why does the one-time binding get called twice? var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.bar = function() { console.log('bar'); return 'bar'; ...

Strip certain tags from HTML without including iframes

Removing specific tags from HTML can be tricky, especially when working with PHP and JavaScript. One approach is to fetch an HTML page in a PHP file using curl and getJSON, storing the result in a .js file. However, this method may encounter issues with mu ...

Using jQuery to add the name of a file to FormData and fetching it in a PHP script

I've been working on a JS code snippet dedicated to uploading images based on their file paths: var data = new FormData(); data.append('fileName', fileName); data.append('file', file); $.ajax({ url : dbPath + "upload-file.php" ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

Tips for updating ng-repeat when the modal is closed?

Scenario: I've got a page (angular) containing a repeater. <tr ng-repeat="row in results.leads"> <td>{{row.SubmittedByName}}</td> Inside the repeater, there's a button in a column that triggers a modal to modify the data o ...

Create a new one-dimensional array by stacking the columns of a matrix

In my current project, I am dealing with a complex array of arrays where each inner array contains objects. My goal is to transform this multidimensional array into a flat array organized in a column-wise order. Here is the code snippet that I have implem ...

Issues with displaying data in Angular ChartJS are troubling users

Currently utilizing Angular 6, my goal is to incorporate a Chart.js line chart. Essentially, I am fetching two arrays from my API: one named weight_data and the other named weight_date, which I then utilize for the chart. After receiving the arrays from t ...

Switch classes while navigating within a div

My website has a sticky sidebar with a list of cars and their corresponding categories in a table: <ul class = "cars"> <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li> ...... ...

clicking on a link with the symbol "#" in the href attribute in Firefox prevents the setter

Good morning everyone, It's early Monday morning and I'm having trouble understanding why this particular line works in Internet Explorer but not in Firefox. <a class="button" href="#" onclick="setMaintenanceMode(false);">disable</a> ...

Error in AngularJS - filterProvider not recognized

When the two script statements below are combined, they cause an error: "Error: [$injector:unpr] Unknown provider: searchNameFilterProvider <- searchNameFilter." Can someone explain why this happens? 1st segment Find Person: <input type="text" ng-m ...