如何仅从顶点着色器移动特定顶点? (以及如何选择它们)

时间:2019-05-13 15:12:12

标签: three.js vertex-shader vertices

我创建了一个像这样的正方形:

  

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

关于材质,我使用了着色器材质。

  

THREE.ShaderMaterial()

在我的vertexShader函数中,我调用了2d噪声函数,该函数可移动正方形的每个顶点,如下所示:

enter image description here

但是最后,我只希望正方形的左侧移动。我认为,如果我只调用50个第一个顶点或每2个调用1个顶点,这应该可行。

这是我的vertexShader的代码:

  

void main(){

     

vUv = uv;

     

vec3 pos = position.xyz;

     

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

     

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

     

}

有人知道我怎么只能选择正方形的左侧顶点?谢谢

1 个答案:

答案 0 :(得分:2)

位置向量在局部空间中映射顶点位置,这意味着四边形的中心在位置(0,0)。

因此,如果您只想将这些更改应用于左侧的顶点,则需要检查顶点的x坐标是否为负x空间。

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);

}

我已经使用了if语句来阐明我的意思,但实际上您应该避免使用它。 这样,您就可以防止在GPU上进行条件分支。