第9.3章:2D颜色替换着色器
颜色替换是2D游戏中常用的技术,可以实现换装系统、队伍标识、昼夜变化等效果。本章将详细介绍各种颜色替换技术的实现。
🎯 学习目标
- 理解颜色替换的基本原理
- 掌握精确颜色匹配和范围替换
- 学会实现调色板交换系统
- 理解HSV颜色空间的应用
💡 颜色替换原理
基础概念
颜色替换通过检测特定颜色并用新颜色替代:
1 2 3 4 5 6
| if (distance(originalColor, targetColor) < threshold) { finalColor = replacementColor; } else { finalColor = originalColor; }
|
替换方式分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| 精确匹配 - 单一颜色替换 范围匹配 - 相似颜色替换 调色板 - 批量颜色映射 HSV调整 - 色调/饱和度修改```
## 🔧 基础颜色替换
### 1. 精确颜色替换
```glsl CCEffect %{ techniques: - name: exact-color-replace passes: - vert: color-replace-vs:vert frag: exact-replace-fs:frag properties: &props mainTexture: { value: white } targetColor: { value: [1, 0, 0, 1], editor: { type: color } } replacementColor: { value: [0, 1, 0, 1], editor: { type: color } } threshold: { value: 0.01, range: [0, 0.5] } featherEdge: { value: 0.005, range: [0, 0.1] } }%
CCProgram color-replace-vs %{ precision highp float; #include <cc-global> in vec3 a_position; in vec2 a_texCoord; out vec2 v_uv; vec4 vert() { v_uv = a_texCoord; return cc_matViewProj * vec4(a_position, 1); } }%
CCProgram exact-replace-fs %{ precision highp float; uniform sampler2D mainTexture; uniform vec4 targetColor; uniform vec4 replacementColor; uniform float threshold; uniform float featherEdge; in vec2 v_uv; vec4 frag() { vec4 originalColor = texture(mainTexture, v_uv); // 计算颜色差异 float colorDistance = distance(originalColor.rgb, targetColor.rgb); // 替换判断 float replaceMask = 1.0 - smoothstep(threshold - featherEdge, threshold + featherEdge, colorDistance); // 颜色混合 vec3 finalColor = mix(originalColor.rgb, replacementColor.rgb, replaceMask); return vec4(finalColor, originalColor.a); } }%
|
📖 本章总结
通过本章学习,我们掌握了:
- ✅颜色替换的基本原理和实现
- ✅精确匹配和范围替换技术
- ✅调色板交换和HSV颜色调整
- ✅队伍颜色系统和动态颜色变化
- ✅完整的TypeScript控制系统
🚀 下一步学习
掌握2D颜色替换着色器后,建议继续学习:
👉 第9.4章:2D描边着色器
💡 实践练习
- 创建一个角色换装系统
- 实现昼夜变化的环境颜色调整
- 开发多队伍对战的颜色标识系统
系列导航