Wednesday, April 2, 2025
spot_img

Gradient Shader Works in 2.4.7 However Not in 3.8.2 – Cocos Creator


Hello,
Right here’s a full part script that may be hooked up to a SIMPLE Sprite node, gradient colours will change each 1 second:

import { _decorator, Colour, Element, macro, Sprite } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('vert_color')
export class vert_color extends Element {
    begin() {
        this.schedule(() => {
            this.updateColor()
        }, 1, macro.REPEAT_FOREVER)
    }
    randomColor1() {
        const COLORS = [Color.BLUE, Color.CYAN, Color.GREEN];
        return COLORS[Math.floor(Math.random() * COLORS.length)]
    }
    randomColor2() {
        const COLORS = [Color.RED, Color.YELLOW, Color.MAGENTA];
        return COLORS[Math.floor(Math.random() * COLORS.length)]
    }
    updateColor () {
        let sprite = this.getComponent(Sprite)
        let vb = sprite['_renderData'].chunk.vb;
        let color1 = this.randomColor1();
        let color2 = this.randomColor2();
        let lb = color1, // left backside
        rb = color1, // proper backside
        lt = color2, // left prime
        rt = color2; // proper prime
        vb[5] = lb.r / 255; vb[6] = lb.g / 255; vb[7] = lb.b / 255; vb[8] = lb.a / 255;
        vb[14] = rb.r / 255; vb[15] = rb.g / 255; vb[16] = rb.b / 255; vb[17] = rb.a / 255;
        vb[23] = lt.r / 255; vb[24] = lt.g / 255; vb[25] = lt.b / 255; vb[26] = lt.a / 255;
        vb[32] = rt.r / 255; vb[33] = rt.g / 255; vb[34] = rt.b / 255; vb[35] = rt.a / 255;
    }
}

Notice that: I exploit 4 colours to assign to 4 nook vertices, in order for you horizontal gradient, simply assign lb and lt to identical worth, rb and rt to identical worth.
For a SIMPLE sprite, vertices are ordered like this in vbo:

SLICED sprite is a little more difficult, its vertices are ordered like this:

subsequently to use a gradient impact, we additionally need to assign vertex colour to all edge vertices and inside vertices (1,2,4,5,6,7,8,9,10,11,13,14) by interpolating colours primarily based on its relative place to nook vertices (0, 3, 12, 15). you may calculate interpolation ratio by accessing node dimension and border values:

uiTransform.contentSize // dimension
sprite.spriteFrame._capInsets // [border left, border top, border right, border bottom]

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -spot_img

Latest Articles