JoshG
JoshG

Reputation: 6735

Change the opacity of a Particle object in Three.js (NOT ParticleSystem)?

I am using the CanvasRendererand Particlein Three.JS. I am generating some random particles using this approach:

texture = THREE.ImageUtils.loadTexture("img.png");

material = new THREE.ParticleBasicMaterial({

    map : texture,
    transparent : true,

});

for (var i = 0; i < pointCount; i++) {

    var particle = new THREE.Particle(material);

    particle.position.x = Math.random() * (max - min) + min;
    particle.position.y = Math.random() * (max - min) + min;
    particle.position.z = Math.random() * (max - min) + min;

    // Set the size of the particle
    particle.scale.x = particle.scale.y = particle.scale.z =  Math.floor(Math.random() * 6) + 2;

    particles.push(particle);
    scatterPlot.add(particle);

}

I would like to (if possible) be able to change the opacity of individual Particles, as I am using transparency as a dimension in my plot (i.e., transparency of a particle reflects the magnitude of a variable). I know I can use particle.material.opacity, but that changes the opacity for all particles. I tried particles[i].material.opacitybut got the same result.

One possibility of course would be to have an array of materials with different opacities. But I'm not sure if there's perhaps a simpler way to do this?

Many thanks!

Upvotes: 0

Views: 2737

Answers (1)

JoshG
JoshG

Reputation: 6735

I think I might have figured this out -- and was simpler than I was thinking. It at least seems to be working for me. I moved the material declaration into the for loop. I think this generates a different ParticleBasicMaterial for each Particle, but I suppose that is okay.

I am then able to access the individual Particle'smaterial by using particles[i].material, which allows me to change the opacity of specific particles.

Here is my updated code:

texture = THREE.ImageUtils.loadTexture("img.png");

for (var i = 0; i < pointCount; i++) {

    material = new THREE.ParticleBasicMaterial({

        map : texture,
        transparent : true,

    });

    var particle = new THREE.Particle(material);

    particle.position.x = Math.random() * (max - min) + min;
    particle.position.y = Math.random() * (max - min) + min;
    particle.position.z = Math.random() * (max - min) + min;

    // Set the size of the particle
    particle.scale.x = particle.scale.y = particle.scale.z =  Math.floor(Math.random() * 6) + 2;

    particles.push(particle);
    scatterPlot.add(particle);

}

// Example opacity change
particles[0].material.opacity = 0.5;

If anyone has any other suggestions, I'd greatly appreciate them. But at least this seems to be giving me the desired behavior for now.

Upvotes: 2

Related Questions