cocosCreator Shader 扑克牌的透视效果

2023-10-23 13:56:54 浏览数 (2)

我这里用的是cocos creator 3.7.2版本,不同版本可能存在差异

看下效果

没有透视:

透视:

从上面两张图还是可以看出差异的~ shader代码

代码语言:javascript复制
// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
CCEffect %{
  techniques:
  - passes:
    - vert: sprite-vs:vert
      frag: sprite-fs:frag
      depthStencilState:
        depthTest: false
        depthWrite: false
      blendState:
        targets:
        - blend: true
          blendSrc: src_alpha
          blendDst: one_minus_src_alpha
          blendDstAlpha: one_minus_src_alpha
      rasterizerState:
        cullMode: none
      properties:
        alphaThreshold: { value: 0.5 }
        u_point: { value: [1,1] }
        u_starty: {value: 0 }
}%
代码语言:javascript复制
CCProgram sprite-vs %{
  precision highp float;
  #include <builtin/uniforms/cc-global>
  #include <builtin/internal/embedded-alpha>
  #if USE_LOCAL
    #include <builtin/uniforms/cc-local>
  #endif
  #if SAMPLE_FROM_RT
    #include <common/common-define>
  #endif
  in vec3 a_position;
  in vec2 a_texCoord;
  in vec4 a_color;

  out vec4 color;
  out vec2 uv0;
  uniform Constant{
    vec2 u_point;   // 自己定义的顶点
    float u_starty; // 扑克牌底边离屏幕下边的距离
  };
  vec4 vert () {
    vec4 pos = vec4(a_position, 1);
    pos.x  = (u_point.x - pos.x) * ((pos.y - u_starty) / u_point.y);
    #if USE_LOCAL
      pos = cc_matWorld * pos;
    #endif

    #if USE_PIXEL_ALIGNMENT
      pos = cc_matView * pos;
      pos.xyz = floor(pos.xyz);
      pos = cc_matProj * pos;
    #else
      pos = cc_matViewProj * pos;
    #endif

    uv0 = a_texCoord;
    #if SAMPLE_FROM_RT
      CC_HANDLE_RT_SAMPLE_FLIP(uv0);
    #endif
    color = a_color;

    return pos;
  }
}%

CCProgram sprite-fs %{
  precision highp float;
  #include <builtin/internal/embedded-alpha>
  #include <builtin/internal/alpha-test>

  in vec4 color;

  #if USE_TEXTURE
    in vec2 uv0;
    #pragma builtin(local)
    layout(set = 2, binding = 12) uniform sampler2D cc_spriteTexture;
  #endif

  vec4 frag () {
    vec4 o = vec4(1, 1, 1, 1);

    #if USE_TEXTURE
      o *= CCSampleWithAlphaSeparated(cc_spriteTexture, uv0);
      #if IS_GRAY
        float gray  = 0.2126 * o.r   0.7152 * o.g   0.0722 * o.b;
        o.r = o.g = o.b = gray;
      #endif
    #endif

    o *= color;
    ALPHA_TEST(o);
    return o;
  }
}%

使用方法

在cocos creator 中找到精灵默认使用的材质ui-sprite-material.mtl,将材质拷贝出来放在自己的资源文件夹下(必须拷贝出来,不然无法修改)。将上面代码保存为gradient.effect,名字按照自己的想法来。最后修改下面4个地方即可

  1. 将精灵的”CustomMaterial”属性设置为你刚刚拷贝出来的材质
  2. 将材质的Effect属性设置为刚刚保存的gradient.effectshader文件
  3. 这里USE TEXTURE一定要勾选上,不然没有纹理,只会显示一张空白图
  4. 调整这三个参数,获得自己想要的透视效果

0 人点赞