What is the best way to rotate the model and randomize it by 90 degrees?

Using a cylinder to draw the tree (data shown in picture one and result in picture one) is straightforward, but incorporating a random rotation of 90 degrees into the tree model poses a challenge.

https://i.sstatic.net/Xh9X6.jpg

Initial input points

//input point 
//Defined as a,b,b,c,b,d......
//Start point, end point, start point, end point...
const line_point = [0, 0, 0,
 2, 151, 2,
 2, 151, 2, 
 -62, 283, 63,
 2, 151, 2,
 62, 297, -58,
 -62, 283, 63,
 -104, 334, 74,
 -62, 283, 63,
 -58, 338, 45,
 62, 297, -58, 
 67, 403, -55,
 62, 297, -58,
 105, 365, -86];

Extracting star and end points

const star_line_x = new Array();
const star_line_y = new Array();
const star_line_z = new Array();

const end_line_x = new Array();
const end_line_y = new Array();
const end_line_z = new Array();

for (var q=0; q < line_point.length; q+=6){
    star_line_x.push(line_point[q]);
}
for (var r=1; r < line_point.length; r+=6){
    star_line_y.push(line_point[r]);
}
for (var s=2; s < line_point.length; s+=6){
    star_line_z.push(line_point[s]);
}

for (var t=3; t < line_point.length; t+=6){
    end_line_x.push(line_point[t]);
}
for (var u=4; u < line_point.length; u+=6){
    end_line_y.push(line_point[u]);

}
for (var v=5; v < line_point.length; v+=6){

    end_line_z.push(line_point[v]);
}
var cylinder_star_point = new Array();
var cylinder_end_point = new Array();

//Connecting star and end points
for (var w=0; w < line_point.length/6; w++){

var star_point = new THREE.Vector3(star_line_x[w], star_line_y[w], star_line_z[w]);
    var end_point = new THREE.Vector3(end_line_x[w], end_line_y[w], end_line_z[w]);
    cylinder_star_point.push(star_point);
    cylinder_end_point.push(end_point);
}

Calculating cylinder height

//Calculate cylinder height
var line_len = new Array();
for (var dd=0; dd < line_point.length/6; dd++){
    var len_x = Math.pow(end_line_x[dd] - star_line_x[dd], 2);
    var len_y = Math.pow(end_line_y[dd] - star_line_y[dd], 2);
    var len_z = Math.pow(end_line_z[dd] - star_line_z[dd], 2);
    var len_direction = Math.sqrt(len_x + len_y + len_z);
    line_len.push(len_direction); //Cylinder height

}

Calculating center point

//Center point
const cylinder_center_point = new Array();
for (var bb=0; bb < cylinder_end_point.length; bb++){
    var star_set_point = cylinder_star_point[bb];
    var end_set_point = cylinder_end_point[bb];
    var center_point = end_set_point.clone().add(star_set_point).divideScalar(2);
    cylinder_center_point.push(center_point);
}

Calculating cylinder direction vector

//Cylinder direction
const cylinder_direction = new Array();
for (var cc=0; cc < cylinder_end_point.length; cc++){
    var star_direction = cylinder_star_point[cc];
    var end_direction = cylinder_end_point[cc];
    var center_direction = end_direction.clone().sub(star_direction);
    cylinder_direction.push(center_direction);
}

Drawing cylinders

   for (var dd=0; dd < cylinder_direction.length; dd++){
    var material = new THREE.MeshPhongMaterial({ color:'#ff0000' });
    let upVector = new THREE.Vector3(0, 1, 0);

    var geometry = new THREE.CylinderGeometry(5, 5, line_len[dd], 20, 1, false); 
    var mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(0, line_len[dd]/2, 0);

    var group = new THREE.Group();
    group.position.set(star_line_x[dd], star_line_y[dd], star_line_z[dd]);
    group.add(mesh);

    let targetVector = cylinder_direction[dd];
    let quaternion = new THREE.Quaternion().setFromUnitVectors(upVector, targetVector.normalize());
    group.setRotationFromQuaternion(quaternion) 
    scene.add(group)
} 

Picture two

https://i.sstatic.net/3RlWi.png

Answer №1

To adjust the orientation of each cylinder mesh, you have two options: either set the rotation.z property individually, or utilize the .lookAt() helper function to align an object with a specific position in space.

Ensure that the object has been added to the scene prior to using the .lookAt() method.

If you're interested, here's an alternative approach for creating a tree structure through recursion and object hierarchy:

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

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Jesting supplier, infusing elements

I find myself in a complex situation that I will do my best to explain, even if it may seem confusing. Imagine I have a customized provider called actionProvider within the module named core. This provider has the ability to register actions and then exec ...

I've been attempting to display information from a mongodb server onto my react application, but unfortunately, it's just not functioning as expected

Below is the error message from the console log: An Error was encountered: Objects are not valid as a React child (found: object with keys {_id, inputText, __v}). If you intended to render a collection of children, please use an array instead. at throwOnIn ...

Angular error TS2339: The property 'before' is not found on type 'HTMLElement' / 'HTMLTextAreaElement' / etc

Objective: My goal is to reposition a div (containing a mat-select dropdown) ABOVE a mat-card-title when the user is accessing the site from a mobile device. If the user is not on a mobile device, the div should remain in its original position to the right ...

The functionality of Angular/Typescript class.name appears to fail during a production build

Using Angular 5, I encountered an unusual problem with the class.name property. We have a TypeScript function as shown below: export class ApiService { public list<T>(c: new(values: Object)=> T) { var cname = c.name; .... } } When ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...

Guide to adjusting alpha transparency in the augmented fragment shader of a Three.js material

I have customized the THREE.MeshStandardMaterial by using onBeforeCompile to modify the shader. The vertex shader is working correctly, but I am struggling to set the alpha/transparency in the fragment shader. Below is the material definition: const mater ...

Properly citing JQuery references

Attempting to incorporate Jquery for the first time, I've encountered an issue. Specifically, I am utilizing VS 2013, asp.net, and VB. Within my head tag, the structure is as shown below. <head runat="server"> <title></title> ...

The response from a Fetch API POST request comes back as a blank text

When I use fetch() to send a post request, the response is coming back empty. Here is my code: JS: async getTotalCompletionTimes() { var res = await fetch("repository/maps.php?method=getcompletiontimes&map="+this.getName(), {method: 'POST&ap ...

Jest unit tests are failing due to an error stating that VUE_APP_CONFIG is not defined

export interface VueAppSettings { BASE_URL: string; BASE_URL_V2: string; } declare const VUE_APP_SETTINGS: VueAppSettings; export const APP_SETTINGS = { ...VUE_APP_SETTINGS } as const; I am encountering a reference error in the code snippet abov ...

One issue I've encountered is that Angularfire seems to have trouble reading the "facebook" property. So my question

I have been developing an android game using the ionic framework and firebase. My goal is to implement a feature where users can log in using Facebook login with Firebase, and then save the game data to the user's database key. The initial part of t ...

Utilize a JSON document in conjunction with running JavaScript code

I have a PHP file that returns JSON data. However, I am looking to include some javascript (specifically Google Analytics code) in the file. Below is the code snippet: <?php header('Content-Type: application/json'); //GOOGLE ANALYTICS ...

Implementing Twin Modals Positioned Side by Side with Bootstrap

My dilemma involves creating two side-by-side modals using Bootstrap's grid logic. I have successfully implemented a single modal with the following code: <div class="modal fade bd-example-modal-lg" tabindex="-1" id="my_modal" role="dialog" aria- ...

Comparing jQuery and Yahoo UI API Design

I find myself puzzled by the contrasting design approaches of jQuery and Yahoo UI APIs. I must confess, I have a strong aversion to the jQuery API, but my knowledge in web programming and JavaScript is limited, so I could be completely mistaken and end up ...

What are the reasons behind loading failures and the subsequent failure to resolve promises?

Here is a snippet of code that is part of a larger directive: var imageArray = []; for (var i = 0; i < $scope.abbreviations.length; i++) { imageArray[i] = new Image(); imageArray[i].src = $scope.abbreviations[i].img ...

Cannot save PDF files to a server using jsPDF

I'm new to this community and still learning javascript & php. I am having trouble saving my PDFs with jsPDF to the local storage on the server (automatically generated). It used to work in the past, but now when I add Canvas (javascript) to my HTML, ...

Having trouble with material-ui installation in React, Redux, and React-Router project

Guide: https://i.stack.imgur.com/k1UMV.png Due to using redux and react router, incorporating MuiThemeProvider at the top of the chain is a bit challenging. What would be the most effective method to integrate this particular library? This is my ReactDO ...

Maximizing the Potential of Return Values in JavaScript

I have a JavaScript code that retrieves information and displays it in a div. It's functioning properly, but I want to dynamically change the div id based on the returned data. For example: function autoSubmit3() { $.post( 'updatetyp ...

Cannot find WoopraTracker within the custom event data

I am currently working on implementing Woopra custom event data upon page load by following their guidelines. I have attempted to push events when the page is ready, however, it keeps returning an error that woopratracker is not defined. Strangely, when ...