Utilizing THREE.js to evenly distribute particles on object surfaces, rather than on vertices

Currently, I have successfully created a particleCloud where the particles are positioned at each vertex of an imported object. However, my goal is to have the particles initially placed on the flat faces of the object instead of in between the vertices and to evenly distribute them on those faces.

In essence, I am aiming for my 3D object to be constructed out of particles

Here is my progress so far:

var loader = new THREE.JSONLoader();
loader.load('./resources/model.json', function (geometry, materials) {

    var material = new THREE.MeshFaceMaterial(materials);
    var model = new THREE.Mesh(geometry, material);

    var particleCount = geometry.vertices.length,
        particles = new THREE.Geometry(),
        pMaterial = new THREE.PointCloudMaterial({
            color: 0xFFFFFF,
            size: 1
        });

    for (var p = 0; p < particleCount; p ++) {
        particle = model.geometry.vertices[p];
        particles.vertices.push(particle);
    }
    particleSystem = new THREE.PointCloud(particles, pMaterial);
    particleSystem.position.set(0, -100, 0)
    particleSystem.scale.set(100,100,100)
    scene.add(particleSystem);

});

EDIT - 1

I've included an image to illustrate what I currently have and my desired outcome. I'm using the front face of a cube as an example, but my object will have more sides.

Answer №1

UPDATE: The previous response is no longer valid.

You now have the option to utilize MeshSurfaceSampler for generating random samples on a mesh's surface.

To access the MeshSurfaceSampler.js script, navigate to the examples/jsm/math directory.

This information pertains to version r.128 of three.js.

Answer №2

To create a 3D object using particles, you must position each particle individually. This process involves setting the x, y, and z coordinates for each particle. For instance, below is a snippet of code that demonstrates how to generate a cube:

var numParticles = 500000;
var geometry = new THREE.BufferGeometry();
var positions = new Float32Array(numParticles * 3);
var colors = new Float32Array(numParticles * 3);

var color = new THREE.Color();

var n = 1000, n2 = n / 2; 

for (var i = 0; i < positions.length; i += 3) {
    var x = Math.random() * n - n2;
    var y = Math.random() * n - n2;
    var z = Math.random() * n - n2;

    positions[i] = x;
    positions[i + 1] = y;
    positions[i + 2] = z;

    var vx = (x / n) + 0.5;
    var vy = (y / n) + 0.5;
    var vz = (z / n) + 0.5;

    color.setRGB(vx, vy, vz);

    colors[i] = color.r;
    colors[i + 1] = color.g;
    colors[i + 2] = color.b;
}

geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));

geometry.computeBoundingSphere();

var material = new THREE.PointCloudMaterial({ size: 15, vertexColors: THREE.VertexColors });

particleSystem = new THREE.PointCloud(geometry, material);
scene.add(particleSystem);

source: this threejs example

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

Utilizing Redux for Efficient Video Player Control

What is the most effective method for managing a video player using Redux, particularly when it comes to dispatching actions to play/pause a video? I am currently working on developing a video player within a React application. I have implemented event li ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

Set the position of a div element to be fixed

I am currently working on a straightforward application that requires implementing a parallax effect. Here are the methods I have experimented with so far: - Inserting an image within a div with the class parallax. - Subsequently, adding an overlay div ...

I'm finding it difficult to understand the reasoning behind the custom hook I created

Looking at the code, my intention is to only execute one of these API requests based on whether origCompId is passed or not. If origCompId is passed as a query parameter, then duplicateInstance should run; otherwise, addNewInstance should be executed. The ...

Seeking assistance to transfer div elements into a different div post an onclick event

I have a container that contains four separate divs. My goal is to append the remaining three divs to another specific div after clicking on one of them. Does anyone know how I can achieve this? <!DOCTYPE html> <html lang="en"> < ...

Is foreach not iterating through the elements properly?

In my code, I have a loop on rxDetails that is supposed to add a new field payAmount if any rxNumber matches with the data. However, when I run the forEach loop as shown below, it always misses the rxNumber 15131503 in the return. I'm not sure what I ...

Changing a live request in React

Imagine you have a request that needs to be delayed, similar to how Google Docs waits a moment before sending the "save" request. In browser JavaScript, you could achieve this by implementing code like the following: // Overwrite this global window variabl ...

Tips for employing numerous if-else conditions utilizing the ternary operator in jsonpath-plus?

JSON { "customer":{ "address":{ "stateRegion":"", "stateRegionCode":"" } } } Code "address.state_code": "$.customer.address.[stateRegion ? state ...

What is the best way to reset the drawing canvas using JavaScript?

Learning HTML for fun! I decided to create a drawing canvas in HTML by following a tutorial on YouTube. You can view the code here: https://jsfiddle.net/MasoodSalik/yr1ezp4x/ Encountering 2 issues: After clearing the canvas, the brush malfunctions as ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

Formik's handleChange function is causing an error stating "TypeError: null is not an object (evaluating '_a.type')" specifically when used in conjunction with the onChange event in DateInput

When using the handleChange function from Formik with the DateInput component in "semantic-ui-calendar-react", I encountered an error upon selecting a date. https://i.stack.imgur.com/l56hP.jpg shows the console output related to the error. AddWishlistFor ...

Error message: When using the Three.JS STL Loader, an Uncaught TypeError occurs because the property 'scale' is being called on an undefined value

I am currently loading five elements using the STL Loader in order to create a table. My goal is to use dat.gui to adjust the scale of Tabletop.STL. Here is the code snippet: <!DOCTYPE html> <html lang="en> <head> <title& ...

Tips for calculating the average of various items within an array

Hello everyone, I'm currently facing a challenge in writing a JavaScript function that calculates the average values for an array of objects. Below is the example array: const array = [ { createdAt: "2021-06-05", value: 0.2 ...

What is the best way to modify or revise meta fields for individual products in order to retrieve multiple images for each product in Shopify?

What is the process for updating or editing meta fields to display multiple images of each product on Shopify? ...

Can AngularJS Filters be used to convert a number into a string, but not the other way around?

After researching Angular JS filters, I discovered that the number filter is used to format a number as a string. However, there doesn't seem to be a built-in filter for converting a string to a number. In an attempt to solve this issue, here is so ...

Navigate the div with arrow keys

Looking for an answer similar to this SO post on moving a div with arrow keys, could a simple and clear 'no' be sufficient: Is it possible to turn an overflowing div into a "default scroll target" that responds to arrow-up/down/page-down/space k ...

Place jQuery popup box in position

After numerous attempts, I still can't seem to find a working solution. All I want is to move my jQuery dialog box down by about 50px from the top of the page. Any suggestions on how to achieve this? function openingDialog() { $("#message").dialo ...

How can I retrieve the value of the last index from the props.data object in React/JS?

My application sends an array object to a child component, allowing access to the data through "props.data". The structure looks like this: ... Parent component (stateless) const myArray = []; for(let i=0; i<rowCount; i++){ myArray.push({ id ...

I encountered a problem when making multiple JSON calls within a for loop

for(var j = 0; j < tempArray.length; j ++){ $.getJSON('http://localhost:8080/predict', tempArray[j]) .fail(function(data,textStatus, error) { Probability = data.responseText; console.error("getJSON failed, status: " + textStat ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...