Search code examples
three.jsvertex-shadervertices

How can I move only specific vertices from my vertexshader ? (And how to choose them)


I created a square like this :

THREE.PlaneBufferGeometry(1, 1, 1, 50);

Regarding its material I used a shader material.

THREE.ShaderMaterial()

In my vertexShader function I call a 2d noise function that moves each vertices of my square like this :

enter image description here

But in the end I only want the left side of my square to move. I think if I only call the 50 first vertices or 1 vertices every 2, this should work.

Here's the code of my vertexShader :

void main() {

vUv = uv;

vec3 pos = position.xyz;

pos.x += noiseFunction(vec2(pos.y, time));

gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);

}

Does anyone know how can I only select the left-side vertices of my square ? Thanks


Solution

  • The position vector maps the vertex position in local-space, which means that the center of the quad is in the position (0,0).

    Therefore, if you want to apply these changes only to the vertices in the left side, you need check if the x coordinate of the vertex is negative x-space.

    void main() {
    
       vUv = uv;
    
       vec3 pos = position.xyz;
    
       if ( pos.x < 0.0 ) {
           pos.x += noiseFunction(vec2(pos.y, time));
       }
    
       // to avoid conditional branching, remove the entire if-block
       // and replace it with the line below
       // pos.x += noiseFunction(vec2(pos.y, time)) * max(sign(-pos.x), 0.0);
    
       gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
    
    }
    

    I've used an if-statement to make it clear what I meant, but in reality you should avoid it. That way you prevent conditional branching on GPU.