动态更改粒子系统中点的颜色

时间:2018-05-01 14:09:55

标签: three.js

我在粒子系统中迭代点,并在点满足某个条件时改变点的颜色。假设我必须将第j个点的颜色更改为黄金:

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

但我没有看到颜色的变化。

这里需要额外的东西吗?

我这样做:

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;

但是粒子的颜色没有反映出来。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

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'

查看有关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.addAttribute('position', new THREE.BufferAttribute(vertices, 3));

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

var points = new THREE.Points(geometry, new THREE.PointsMaterial({
  size: 0.25,
  vertexColors: THREE.VertexColors
}));
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);
}
&#13;
body {
  overflow: hidden;
  margin: 0;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="btnColor" style="position: absolute">Colorify</button>
&#13;
&#13;
&#13;