Mandroid
Mandroid

Reputation: 7478

Changing color of points in a particle system dynamically

I am iterating through points in a particle system, and changing a point's color when point satisfies a certain condition. Say I have to change color for jth point to gold:

var colors = particlesystem.geometry.attributes.color.array;
colors[3*j] = 0;
colors[3*j+1] = 40;
colors[3*j+2] = 255;

But I don't see change in color.

Is any thing extra is needed here?

I do as:

geometry.attributes.color.array[3*j] = r;
geometry.attributes.color.array[3*j] = g;
geometry.attributes.color.array[3*j] = b;
geometry.attributes.color.needsUpdate = true;

But no change is reflected in particles' color.

Upvotes: 1

Views: 1139

Answers (1)

prisoner849
prisoner849

Reputation: 17586

You can do it this way:

var colors = particlesystem.geometry.attributes.color;
colors.setXYZ(j, 0, 0.15, 1);
colors.needsUpdate = true; // when you change values of an attribute, set this flag to 'true'

Have a look at the documentation about THREE.BufferAttibute().

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(2, 5, 10);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var geometry = new THREE.BufferGeometry();
var vertices = new Float32Array([-1.0, -1.0, 1.0,
  1.0, -1.0, 1.0,
  1.0, 1.0, 1.0, -1.0, 1.0, 1.0
]);

geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));

var colors = [];
for (var i = 0; i < geometry.attributes.position.count; i++) {
  colors.push(1, 1, 1);
}
geometry.setAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));

var points = new THREE.Points(geometry, new THREE.PointsMaterial({
  size: 0.25,
  vertexColors: true
}));
scene.add(points);

btnColor.addEventListener("click", function() {
  geometry.attributes.color.setXYZ(2, 0, 0.15, 1);
  geometry.attributes.color.needsUpdate = true;
}, false);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="btnColor" style="position: absolute">Colorify</button>

Upvotes: 2

Related Questions