以下是在Cocos Creator中实现字体发光效果的着色器示例:
1. 创建发光着色器材质
```glsl
// effect/font-glow.effect
CCEffect %{
techniques:
- name: opaque
passes:
- vert: vs
frag: fs
properties:
mainTex: { value: white }
glowColor: { value: [1, 1, 0, 1] }
glowIntensity: { value: 1.0 }
glowWidth: { value: 0.1 }
}%
CCProgram vs %{
precision highp float;
#include
#include
in vec3 a_position;
in vec2 a_texCoord;
in vec4 a_color;
out vec2 v_texCoord;
out vec4 v_color;
void main() {
vec4 pos = vec4(a_position, 1);
pos = cc_matViewProj * pos;
gl_Position = pos;
v_texCoord = a_texCoord;
v_color = a_color;
}
}%
CCProgram fs %{
precision highp float;
#include
uniform UARGS {
vec4 glowColor;
float glowIntensity;
float glowWidth;
};
in vec2 v_texCoord;
in vec4 v_color;
uniform sampler2D mainTex;
void main() {
// 原始纹理颜色
vec4 texColor = texture(mainTex, v_texCoord);
// 发光效果计算
float glowMask = 0.0;
for (float x = -1.0; x <= 1.0; x += 1.0) {
for (float y = -1.0; y <= 1.0; y += 1.0) {
vec2 offset = vec2(x, y) * glowWidth;
vec4 offsetColor = texture(mainTex, v_texCoord + offset);
glowMask += step(0.1, offsetColor.a);
}
}
// 发光强度和颜色
glowMask = clamp(glowMask, 0.0, 1.0);
vec4 glowResult = glowColor * glowMask * glowIntensity;
// 混合原始颜色和发光颜色
vec4 finalColor = texColor + glowResult;
finalColor.a = texColor.a;
gl_FragColor = finalColor * v_color;
}
}%
```
2. TypeScript组件设置
```typescript
import { _decorator, Component, Material, Label } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('FontGlowEffect')
export class FontGlowEffect extends Component {
@property({ type: Material })
glowMaterial: Material | null = null;
start() {
const label = this.getComponent(Label);
if (label) {
// 应用发光材质
label.material = this.glowMaterial;
}
}
// 动态调整发光效果
setGlowParams(color: Color, intensity: number, width: number) {
if (this.glowMaterial) {
this.glowMaterial.setProperty('glowColor', color);
this.glowMaterial.setProperty('glowIntensity', intensity);
this.glowMaterial.setProperty('glowWidth', width);
}
}
}
```
3. 使用步骤
a. 在Cocos Creator中创建自定义材质
- 创建材质
- 选择上面的着色器代码
- 配