Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter.

var particleCount = 14,
particles = new THREE.Geometry(),
pMaterial = new THREE.PointsMaterial({
  map: new THREE.TextureLoader().load("x.png"),
  blending: THREE.multiplyBlending,
  flatShading: true,
  size: 40,
  transparent: true,
  depthTest: true,
  sizeAttenuation: true,
  opacity: 1
});
var particleSystem;

I am confused because despite setting transparency, I am unable to adjust the value within the update function I created for my emitter.

function update() {

//particleSystem.rotation.y += 0.01;
 pCount = particleCount;
 while (pCount--) {
 particle = particles.vertices[pCount];

(This is where a lot of validation is for the points)

 particleSystem.geometry.verticesNeedUpdate = true;
 particleSystem.rotation.y += (Math.random()*0.001)

}

Render loop:

renderer.setAnimationLoop(() => {
 update();
 composer.render(scene, camera);
});

I aim to have the particles fade out and not be visible in the scene for about 20 pixels, and then fade back in. However, I am unsure of how to modify the opacity as simply doing particle.opacity += 0.1 does not work.

Edit: I am also hesitant about adjusting the size, as I want to do a similar transition from 20 to 40. I could potentially base it on its Y coordinate. Nonetheless, I am unsure how to gradually change that as well.

Apologies if this question seems obvious or repetitive, I appreciate any assistance I receive. Any alternative approaches that I have come across are structured differently or involve arrays, which I am unsure how to implement in my desired way.

(Thank you in advance)

Answer №1

An important concern lies in the fact that the opacity and size are attributes of the THREE.PointsMaterial. To allow points to have varying sizes, it is necessary to create a collection of distinct THREE.Points each with its own unique THREE.PointsMaterial.

To achieve this, generate an array of THREE.Points with diverse materials:

var texture = new THREE.TextureLoader().load( "..." );

var particleSystemCount = 14;
var particleSystems = [];
for (var i = 0; i < particleSystemCount; ++ i) {
    var geometry = new THREE.Geometry();
    var pMaterial = new THREE.PointsMaterial({
        size: 20,
        map: texture,
        blending: THREE.AdditiveBlending,
        transparent: true,
        depthTest: false,
        sizeAttenuation: true,
        opacity: 0
    });

    // ...        

    var points = new THREE.Points(geometry, pMaterial);
    scene.add(points);   
    particleSystems.push(points);
}

Then, in the update function, adjust the opacity and size of each point system independently:

function update() {

    for (var i = 0; i < particleSystems.length; ++ i) {
        var points   = particleSystems[i];

        var material = points.material;
        var particle = points.geometry.vertices[0];

        // ....

        if ( material.size < 40 )
            material.size += 0.5;
        if ( material.opacity < 1 )
            material.opacity += 0.01;

        // ....
    }
}

var canvas_w = window.innerWidth, canvas_h = window.innerHeight;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, canvas_w/canvas_h, 1, 1000);
camera.position.set(0, 0, 400);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(canvas_w, window.innerHeight);
document.body.appendChild(renderer.domElement);
window.onresize = function() { 
    canvas_w = window.innerWidth, canvas_h = window.innerHeight;
    renderer.setSize(canvas_w, canvas_h);
    camera.aspect = canvas_w/canvas_h;
    camera.updateProjectionMatrix();
}

var texture = new THREE.TextureLoader().load("https://threejs.org/examples/textures/sprites/circle.png");

var particleSystemCount = 14;
var particleSystems = [];
for (var i = 0; i < particleSystemCount; ++ i) {
    var geometry = new THREE.Geometry();
    var pMaterial = new THREE.PointsMaterial({
        size: 20,
        map: texture,
        blending: THREE.AdditiveBlending,
        transparent: true,
        depthTest: false,
        sizeAttenuation: true,
        opacity: 0
    });
    var px = (Math.random() - 0.5) * 100;
    var py = (Math.random() - 0.5) * 100 + 200;
    var pz = (Math.random() - 0.5) * 100;
    var particle = new THREE.Vector3(px, py, pz);
    particle.velocity = new THREE.Vector3(0, 0, 0);
    geometry.vertices.push(particle);
    var points = new THREE.Points(geometry, pMaterial);
    scene.add(points);   
    particleSystems.push(points);
}

function update() {

    for (var i = 0; i < particleSystems.length; ++ i) {
        var points   = particleSystems[i];
        
        var material = points.material;
        var particle = points.geometry.vertices[0];

        if (particle.y < -200) {
              particle.x = (Math.random() - 0.5) * 100;
              particle.y = (Math.random() - 0.5) * 100 + 200;
              particle.z = (Math.random() - 0.5) * 100;
              particle.velocity.y = 0;
              material.size = 20;
              material.opacity = 0;
        }
        
        particle.velocity.y -= Math.random() * .1;
        particle.add(particle.velocity);

        
        if ( material.size < 40 )
            material.size += 0.25;
        if ( material.opacity < 1 )
            material.opacity += 0.01;

        points.geometry.verticesNeedUpdate = true;
        points.rotation.y += (Math.random()*0.001)
    }
}

renderer.setAnimationLoop(() => {
    update();
    renderer.render(scene, camera);
});
body { overflow: hidden; margin: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js"></script>

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

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

Troubden array filtration in Angular is malfunctioning

I recently developed an angular "filter component" intended to filter an array and display its contents. The keyword used to filter the array, value, is obtained from another component through a service. While the HTML displays both the value and the entir ...

Express is encountering a non-executable MIME type of 'text/html' with Webpack

My express application setup is as follows: const express = require("express"); const app = express(); const server = require("http").Server(app); const path = require("path"); const port = process.env.PORT || 5000; app.use(& ...

Challenges with conditional statements in JavaScript

This is a simple code snippet for a ToDo-List application. The function InputCheck() is designed to validate if the input bar contains any value. If the input bar is empty, the function should not trigger the addTodo function. However, in its current stat ...

Why isn't my output being shown on the screen?

Why is the output (refresh value) not being displayed? function myFunction() { $a = document.getElementById("examplehtml").value; document.write("<big><bold>"); document.write($a); document.write("</bold></big>"); $b = ...

Obtain scope in AngularJS using object ID

Is it possible to retrieve the specific scope of an object by accessing it through an ID? I am currently using angular ui tree for a navigation menu. However, I face an issue where after adding a subitem and saving the navigation into a mysql database, th ...

Ways to fix the issue of an unspecified user error in authjs

Having trouble with creating a web token using passport LocalStrategy and passport-jwt. I keep getting a user undefined error in auth.js ****401 Unauthorized**** (if (!user) { return res.json(401, { error: 'message' });}). How can I fix this issu ...

Changes made to the data are not reflected in the user interface, but they are visible in the console

When working on a React project with input fields, I encountered an issue where the date data can be changed but doesn't get reflected in the UI. Instead, the updated data is visible in the console. The code snippet below showcases how I'm using ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Toggle a div using jQuery with a distinctive identifier

I need to display all products that a client has ordered from the database and I want to be able to show/hide them when clicking on a specific div element. http://prntscr.com/7c5q6t Below is my PHP code which displays all the ordered products: <td cla ...

The gauge created dynamically using the justgage plugin does not display the value

I am currently experimenting with dynamically adding gauges, and although they are displayed on the screen, the values being shown are incorrect. Even when the graph indicates a different value, it still displays 0. These gauges are triggered by an onclick ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

Iterating through data to showcase vertical columns for a specific time span of 3 years, highlighting only the months with available data

If data has been available for every month over the past 3 years, I need it to be displayed in a specific format. You can refer to this example fiddle for reference: https://jsfiddle.net/bthorn/ncqn0jwy/ However, there are times when certain months may no ...

How should one properly utilize the app and pages directories in a next.js project?

For my current next.js 13 project, I have decided to utilize the /pages directory instead of /app. Nonetheless, I recently included the app directory specifically for its new features related to dynamic sitemap rendering. Do you think this approach is app ...

retrieving the outcome from a PHP script invoked through Ajax

Having trouble transferring the results of a PHP script to HTML input fields This is my PHP script: $stmt->execute(); if ($stmt->rowCount() > 0){ $row = $stmt->fetch(PDO::FETCH_ASSOC); echo 'Located: ' . $row[&ap ...

Discover the best way to retrieve XML information from various sources specifically designed for Windows gadgets using JavaScript

I have previously visited this site and have not been able to locate a solution that I believe will be suitable for my Windows 7 desktop gadget. In essence, I am seeking a method to retrieve XML data from weather.gov using Javascript (or any other means t ...