问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Cocos Shader入门学习案例:实现物体消融效果

创作时间:
作者:
@小白创作中心

Cocos Shader入门学习案例:实现物体消融效果

引用
CSDN
1.
https://m.blog.csdn.net/weixin_52985165/article/details/137857476

本文将介绍如何使用Cocos引擎实现物体的消融效果。通过在Shader中添加噪声图属性,修改片段着色器代码,并使用脚本控制节点的消融过程,可以实现物体逐渐消失的视觉效果。

Shader配置

在CCEffect中添加以下属性:

properties:
    dissolveMap: { value: white, editor: { tooltip: '噪音图'} }
    dissolveThreshold: { value: 0.3, editor: { tooltip: '溶解阈值'} }
    edgeColor: { value: [1, 1, 1, 1] ,editor: { type: color, tooltip: '边缘颜色'}}
    edgeWidth: { value: 0.05, editor: { tooltip: '边缘宽度'} }

片段着色器修改

声明部分

#if USE_TEXTURE
uniform sampler2D dissolveMap; // 噪音图
#endif
uniform Dissolve {  // 消融相关
    vec4 edgeColor;
    float edgeWidth;
    float dissolveThreshold;
};

入口函数

void main () {
    vec4 o = vec4(1, 1, 1, 1);
    #if USE_TEXTURE
      vec4 dissolveValue = texture2D(dissolveMap, v_uv0);
      if (dissolveValue.r < dissolveThreshold) { // 溶解
        discard;
      }
      
      o = texture2D(texture, v_uv0);
    #endif
    o *= v_color;
    if (dissolveValue.r < dissolveThreshold + edgeWidth && o.a > 0.0) { // 边缘
      float edge = smoothstep(dissolveThreshold - edgeWidth, dissolveThreshold + edgeWidth, dissolveValue.r);
      vec4 finalColor = mix(o, edgeColor, edge);
      o = finalColor;
    }
    gl_FragColor = o.rgba;
}

脚本控制

使用以下脚本控制节点的消融过程:

const {ccclass, property} = cc._decorator;
@ccclass
export default class DissolveEffect extends cc.Component {
    @property
    dissolveInterval: number = 0.01;
    @property
    dissolveStep: number = 0.01;
    start () {
        const material = this.getComponent(cc.Sprite).getMaterial(0);
        material.setProperty('dissolveThreshold', 0);
        
        this.schedule(()=>{
            let dissolveThreshold = material.getProperty('dissolveThreshold', 0);
            dissolveThreshold += this.dissolveStep;
            material.setProperty('dissolveThreshold', dissolveThreshold);
            // console.log(dissolveThreshold);
            
        }, this.dissolveInterval, 1/this.dissolveStep);
    }
}

最终效果

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号