0
\$\begingroup\$

I am trying to achieve the effect of having a points cloud with moving points while also keeping them confined within a sphere of radius X.

I have managed to do it without using shaders but I want to try and do it with shaders as well.

What I have so far is this

const uniforms = {
  u_time: { value: 0 },
  u_radius: { value: 1500 },
};

const vShader = `
uniform float u_time;
uniform int u_radius;

attribute vec3 velocity;

varying vec3 v_position;

void main() {
  v_position = position;
  vec3 vel = velocity * u_time;
  
  if(length(position) > float(u_radius)) {
    vel = vel * -1.0;
  }
  
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position + vel, 1.0);
  gl_PointSize = 10.0;
}`;

const fShader = `
varying vec3 v_position;

void main() {
  vec3 color = vec3(1.0);
  gl_FragColor = vec4(color, 0.7);
}`;

The logic is that for each vertex, I am comparing its length based on its current position to the sphere radius and if it falls outside of it its velocity vector should be negated ,thus keeping it within the sphere.

Sadly what I have above does not seem to work, as the particles spread out to infinity over time.

I am new to three.js and GLSL so I must be missing something obvious and doing this wrong.

EDIT:

Shown in the gif: The effect as I have currently managed to implement it using Points, and an array of positions and an array of velocities (these are seeded once during initialisation with random values)

(it may be hard to see in the gif due to compression, but each particle is moving randomly but is always contained within the sphere)

On every tick I iterate over the array of particles and add their velocity vector to their position vector. If their position vector length is > than the sphere radius I negate the velocity vector and update the velocities array to the indices that correspond to that particle. I then mark the Points geometry position attribute as needing an update and that's it.

particles with random velocity contained within a sphere

\$\endgroup\$

0

You must log in to answer this question.

Browse other questions tagged .