CocosCreator Shader学习(一):描边效果

最近研究了一下CocosCreator的shader使用方法,并把自己学习期间写的一些效果分享出来。

CocosCreator版本:v2.3.2

官方学习链接:Material 材质介绍、Effect介绍(官方文档是最好的学习文档,一定要反复多看)

描边效果

原理:1.判断图片中的某个点周围8个点的alpha值。2.判断某点是否处于图片边缘。

CocosCreator Shader学习(一):描边效果_第1张图片

CocosCreator Shader学习(一):描边效果_第2张图片

CocosCreator Shader学习(一):描边效果_第3张图片

如上3图就是给精灵换材质并选定自定义的Effect。

顶点着色器代码不用修改。

片元着色器代码如下:

CCProgram fs %{
  precision highp float;
  
  #include 
  #include 

  in vec4 v_color;

  #if USE_TEXTURE
  in vec2 v_uv0;
  uniform sampler2D texture;
  #endif

  //cocos规定在shader中所有非sampler的uniform都应以block形式声明
  uniform InputData{
    float outlineWidth;  //外部程序输入描边宽度1-1.0。
  };

  //检查pos点是否需要描边
  bool checkIsMakeOutline(vec2 pos){
    //alpha检测值
    float alpha = 0.1;
    vec4 color = texture(texture, pos);
    if(color.a <= alpha || outlineWidth == 0.0)return false;

    //检测当前点周围的8个点的alpha值
    color = texture2D(texture, pos + vec2(0, outlineWidth));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(outlineWidth, outlineWidth));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(outlineWidth, 0));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(outlineWidth, -outlineWidth));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(0, -outlineWidth));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(-outlineWidth, -outlineWidth));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(-outlineWidth, 0));
    if(color.a <= alpha)return true;
    color = texture2D(texture, pos + vec2(-outlineWidth, outlineWidth));
    if(color.a <= alpha)return true;
    
    //当前点已是纹理边缘
    if(pos.x <= outlineWidth || pos.x >= 1.0 - outlineWidth)return true;
    if(pos.y <= outlineWidth || pos.y >= 1.0 - outlineWidth)return true;

    return false;
  }

  void main () {
    vec4 o = vec4(1, 1, 1, 1);

    #if USE_TEXTURE
    o *= texture(texture, v_uv0);
      #if CC_USE_ALPHA_ATLAS_TEXTURE
      o.a *= texture2D(texture, v_uv0 + vec2(0, 0.5)).r;
      #endif
    #endif

    o *= v_color;

    ALPHA_TEST(o);

    if(checkIsMakeOutline(v_uv0)){
      //检查到v_uv0点需要描边,直接改变颜色值
      o = vec4(1, 0, 0, 1);
    }

    gl_FragColor = o;
  }
}%

注释写的很详细,大家应该都看得懂。

运行效果图如下:

CocosCreator Shader学习(一):描边效果_第4张图片

如果大家描边宽度在编辑器中显示和运行起来的效果相差很大(这个坑,在论坛看了很多大神的帖子,才爬出来)。

主要原因:cocos运行的时候默认会自动合图,合图之后导致Effect中接收到的纹理uv坐标不是单个图的纹理坐标,大概就是这个意思吧。

解决方法:取消单个图自动合图。

CocosCreator Shader学习(一):描边效果_第5张图片

 

 

你可能感兴趣的:(CocosCreator,Shader)