Generate a vector3 with a defined direction

I have a challenge at hand where I am looking to create a 2D flow field in three.js based on a working example I found in p5.js. The original source code for reference is as follows:

var inc = 0.1; //Increment of noise
var yoff = 0;
var scl = var; //Scale of noise field 
var cols = rows = 10; 

for(var y = 0; y < rows; y++)
{
    var xoff = 0;
    for(var x = 0; x < cols; x++)
    {
        var index = x + y * cols;
        var angle = noise(xoff, yoff) * TWO_PI; //Create angle with Perlin noise
        var v = p5.Vector.fromAngle( angle ); //Create new vector from angle
        v.setMag( 0.1 ); //set magnitude of vector
        flowfield[index] = v;
        xoff += inc;
        stroke(0, 50);
        strokeWeight(1);
        push();
        translate(x * scl, y * scl);
        rotate(v.heading());
        line(0, 0, scl, 0);
        pop();
    }
    yoff += inc;
}

My goal now is to replicate the functionality of p5.Vector.fromAngle() function in three.js.

From what I gather, I need to create a vector and then perform rotation around the z-axis using .applyQuaternion(quaternion). However, my struggle lies in rotating the vector around the center without changing its heading.

var vector = new THREE.Vector3( 100, 100, 0 );

var angle = Math.random() * Math.PI * 2;
var quaternion = new THREE.Quaternion();
quaternion.setFromAxisAngle( new THREE.Vector3( 0, 0, 1 ), Math.PI / 2 );

vector.applyQuaternion( quaternion );

Answer №1

If you simply want to utilize the x/y-plane, the function would appear as follows:

function generateVectorFromAngle(angle) {
  return new THREE.Vector3(
    Math.cos(angle), Math.sin(angle), 0
  );
}

In my opinion, this method is much more straightforward compared to using quaternions for this purpose. If your needs involve more intricate three-dimensional rotations, then quaternions are definitely the way to go. This approach is also in line with what p5.js does.

The function will output a unit vector (a vector with length 1) pointing towards the specified direction (thus,

generateVectorFromAngle(0) === [1, 0, 0]
,
generateVectorFromAngle(Math.PI/2) === [0, 1, 0]
, etc.).

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

Both of the radio buttons in Material-UI have been selected

I have a unique document that showcases an implementation of RadioGroup, FormControlLabel, and FormControl. Take a look at the code snippet below for reference. import React from 'react'; import PropTypes from 'prop-types'; import Radio ...

How can I effectively develop a versatile user interface for a website using Ruby on Rails that is compatible with all

Currently, I am in the midst of developing a web application using Ruby on Rails. Occasionally, I encounter challenges with cross-browser compatibility when it comes to CSS and Javascript. Are there any strategies you recommend to reduce these issues dur ...

Access a specific element within an array using Handlebars.js

After converting a CSV to JSON, I have data that looks like this: [["Year","Make","Model","Description","Price"],["1997","Ford","E350","ac, abs, moon","3000.00"],["1999","Chevy","Venture \"Extended Edition\"","","4900.00"],["1999","Chevy","Ventu ...

Regex tips: Matching multiple words in regex

I am struggling with creating a simple regex. My challenge is to write a regex that ensures a string contains all 3 specific words, instead of just any one of them: /advancebrain|com_ixxocart|p\=completed/ I need the regex to match only if all thre ...

Obtaining distinct form control values for replicated form fields with Angular

Issue with Dynamic Form Duplicates: I am currently working with a reactive form that has two fields - name and value. There is an add button that duplicates the form by copying these fields. The challenge I am facing is with updating the values of the dup ...

How to choose the second anchor element in a list with Protractor

I am facing a challenge where I need to click on the 2nd anchor tag in a list of anchor tags. <ul id="shortcuts"> <li><a ui-sref="app.journeyExplorer" href="#/journey-explorer/"><span class="ng-binding">1</span></a> ...

What is the best way to display the elements of an array within an HTML div element?

I've been trying to display the contents of an array in a div container on my HTML file, but I'm stuck. Here's what I currently have: function printArray() { var $container = $('.container'); $container.html(''); ...

Performing a NodeJS MySQL query using chain promises

I have a set of 3 functions that I need to call step by step. For example, after calling the first function and getting a result, I must then call the second function and pass the parameter returned from the first call. Once the second call is completed, I ...

The textures in three.js material do not interact with lighting sources

I am curious about whether a textured geometry can be successfully lit in three.js. In my current scene, I have noticed that all materials receive lighting effectively when using spotLight and directionalLight, except for those that have a texture applied ...

Trigger a Redux action with the following action as the payload in order to display a Material UI snackbar or dialog

Currently, my project involves using React along with Redux and Material UI to develop a web application. The web app consists of numerous pages and components. It is common practice to have a snackbar or dialog interact directly with the user's actio ...

What is the most effective method for nesting loops in NodeJS and Mocha?

Currently, I am attempting to create a loop within a loop in my NodeJS code, but I seem to be getting lost along the way. The results are not as expected - sometimes callbacks are triggered twice and so on. My approach involves using the async module. I wo ...

convert an array into a JSON object using JavaScript

Is there a way to convert the following array structure arr = [{ "a":1, "b":2, "c":c }] into a JSON object format? arr = { "a":1, "b":2, "c":c } ...

Invoke React Component Function using onclick in dangerouslySetInnerHTML

I'm new to React and I have a contenteditable div with dangerouslySetInnerHTML as the child, for formatting user input at runtime. When a specific span is clicked inside the HTML, I want to update a variable in the parent component using setState. Is ...

Modify Chartjs label color onClick while retaining hover functionality

Currently, I have implemented vue-chart-js along with the labels plugin for a donut chart. Everything is working well so far - when I click on a section of the donut chart, the background color changes as expected. However, I now want to also change the fo ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

Surprising Media Component Found in URL Parameters within the design

Exploring the page structure of my Next.js project: events/[eventId] Within the events directory, I have a layout that is shared between both the main events page and the individual event pages(events/[eventId]). The layout includes a simple video backgro ...

Automatically updating quantity with the power of jQuery

I have created a spreadsheet where users can input their expenses and the total will update automatically. Initially, I have set some default numbers in my HTML which are editable for users to modify as needed. However, I am facing an issue with my JQuer ...

How can I change the background color of a parent div when hovering over a child element using JavaScript

I am working on a task that involves three colored boxes within a div, each with a different color. The goal is to change the background-color of the parent div to match the color of the box being hovered over. CSS: .t1_colors { float: left; wid ...

Executing a function upon loading a page triggered by a submitted form

Recently on my index.php page, I implemented a form that posts data into a third-party newsletter system. After the form submission, the page reloads to index.php?mail&. Is there a way to detect when the page is loaded and determine if the form has bee ...