Changing the color of specific sprites in three.js

I'm currently exploring three.js and encountering some difficulties when attempting to adjust the color of individual sprites in an array.

My reference point is the example provided on this link from threejs.org.

The specific task I am working on involves changing the color of each sprite based on its scale value. To achieve this, I inserted the following line of code into the final function within the source file:


function render() {

    camera.position.x += ( mouseX - camera.position.x ) * .05;
    camera.position.y += ( - mouseY - camera.position.y ) * .05;
    camera.lookAt( scene.position );

    var i = 0;

    for ( var ix = 0; ix < AMOUNTX; ix ++ ) {

        for ( var iy = 0; iy < AMOUNTY; iy ++ ) {

            particle = particles[ i++ ];
            particle.position.y = ( Math.sin( ( ix + count ) * 0.3 ) * 50 ) +
                ( Math.sin( ( iy + count ) * 0.5 ) * 50 );
            particle.scale.x = particle.scale.y = ( Math.sin( ( ix + count ) * 0.3 ) + 1 ) * 4 +
                ( Math.sin( ( iy + count ) * 0.5 ) + 1 ) * 4;

            // Added this line in an attempt to change color based on scale //
            particle.material.color.setHSL(particle.scale.x * .1, .2, .2);

        }

    }

    renderer.render( scene, camera );

    count += 0.1;

}

Despite my efforts, the additional line altered all particles to have identical color values. I presumed that each element in the array would be accessed and modified within the loop, yet this does not appear to be the case.

Answer №1

All of the particles are interacting with the shared material,

            var material = new THREE.SpriteCanvasMaterial( {

                color: 0xffffff,
                program: function ( context ) {

                    context.beginPath();
                    context.arc( 0, 0, 0.5, 0, PI2, true );
                    context.fill();

                }

            } );

Ensure this code is placed above the loop responsible for creating sprite particles to assign each one a unique material.

Answer №2

The advice on assigning each sprite its own material really helped me make progress. By creating an array for materials and establishing a connection between each material and sprite element, I was able to move in the right direction.

            var x = 0;
            var y = 0;

            for ( var ax = 0; ax < TOTALX; ax ++ ) {

                for ( var ay = 0; ay < TOTALY; ay ++ ) {

                    materials[ y ] = new THREE.SpriteCanvasMaterial( {

                    vertexColors: THREE.VertexColors,
                    program: function ( ctx ) {

                        ctx.beginPath();
                        ctx.arc( 0, 0, 0.5, 0, TWO_PI, true );
                        ctx.fill();

                     }

                    } );

                    part = particles[ x ++ ] = new THREE.Sprite( materials[ y ++ ] );
                    part.position.x = ax * OFFSET - ( ( TOTALX * OFFSET ) / 2 );
                    part.position.z = ay * OFFSET - ( ( TOTALY * OFFSET ) / 2 );
                    scene.add( part );

                }

            }

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

Use JQuery to locate and remove all commas within an unordered list, replacing them with empty spaces

Web Development <ul class="tabbox"> <li></li> , <li></li> , <li></li> </ul> Problem with JQuery Implementation $(".tabbox").replace(',' , ''); // I ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

Tips for Sharing Multiple Nested Arrays in AngularJS

I am working with an array in AngularJS, and here is an example: $scope.order.qty='20'; $scope.order.adress='Bekasi'; $scope.order.city='Bekasi'; To post this array, I use the following code: $http({ method : &ap ...

CSS transition fails to revert

My standard opacity animation is not working in reverse order. Here is a link to the JSFiddle example. According to the documentation, it should work automatically. Since I am new to JavaScript, I am unsure if this issue lies in my code or if the CSS anima ...

What is the method for setting required to true only when the user meets a specific condition?

Hello, I am creating models for my mongodb. I want the birthday field to be required only if the user being added is a student. If the user is a teacher, it is okay if no birthday is provided. const userSchema = mongoose.Schema({ 20 21 _id: m ...

No need for jQuery with this scrolling image gallery

I recently created a horizontal scrolling image gallery with thumbnails underneath. The goal is to click on a thumbnail and have the corresponding image scroll into view. Here's the HTML setup: <div class="images_container"> <img id="imag ...

Steps on removing a file type from a Material UI textfield

I've been struggling to figure out how to clear a Material UI textfield with type="file" even after trying multiple approaches. My issue arises when I set a file size limit and display an error message if a user tries to upload a file larg ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

Jquery form calculation not matching up

I've been struggling to make this jQuery math function work with my form. The snippet works fine, but when I try to integrate it into the actual form, I can't seem to get it aligned properly to perform the required calculations. Any suggestions ...

Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible. I have been given an assignment that requires me to ut ...

The instance does not have a definition for the property or method "names" that is being referenced during rendering

Currently, I'm working on developing a CRUD application using Vue.js and Firebase. However, I've encountered an error that I can't seem to resolve: [Vue warn]: Property or method "names" is not defined on the instance but referenced during r ...

Need to update various form fields at once with jquery?

There is a form with fields for firstname, lastname, email, country, along with edit icon and submit/cancel buttons. When the user clicks on the edit icon in the top right corner, all values will be displayed in textboxes and the country will be shown in ...

Exploring alternatives to ref() when not responsive to reassignments in the Composition API

Check out this easy carousel: <template> <div ref="wrapperRef" class="js-carousel container"> <div class="row"> <slot></slot> </div> <div class=&q ...

discord.js fails to provide a response

const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Clien ...

Displaying error message dynamically using ajax

I am looking to customize the way error messages are displayed on my form. Instead of having one generic div above the whole form, I want the error messages to appear next to each input field. <div id="response"><!--This section will show error ...

Dramatist: What are effective methods for distinguishing and monitoring frames within a webpage?

When it comes to storing my own copy of frames, I want to utilize the page.on("frameattached") and page.on("framedetached") events to properly manage the lifecycle of the frames. My main concern is how I can uniquely identify them across these events. I ...

Providing data from a javascript xml file upon page initialization

I am aiming to extract multiple values from an XML file as soon as an HTML page is loaded. The XML file remains constant and will not change over time. It will be stored in the same directory as the HTML page. The purpose of this XML file is to fill severa ...

Enhance the editing capabilities of the Json data form

https://i.stack.imgur.com/YZIjb.png My goal is to enhance a form for editing json data by moving beyond the typical <textarea /> tag and making it more user-friendly. Are there any tools available that can help improve the form's usability? Add ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...

Angular Translate Directive Unleashes the Power of XSS Vulnerabilities

For my project, I have chosen to utilize the 'escape' method as the sanitization strategy for handling potentially harmful content. This includes implementing the translate directive in certain areas, as well as utilizing the translate filter in ...