Siberhecy
Siberhecy

Reputation: 621

How to replace colors with textures via Shaders in Unity 3D

I have a problem. I tried to search but I can't find what I want. I have a texture. This texture have a blue, green and black colors. They are masks, this is a face texture actually. I want to replace them like blue color will replace with my eyes texture in unity, green color will replace with face texture.. How can I write this shader? I searched but only I find color changing shaders :( Thanks..

Upvotes: 0

Views: 2871

Answers (1)

Kalle Halvarsson
Kalle Halvarsson

Reputation: 1268

The way i interpret your question is that you want a shader where one texture serves as a mask, blending between 3 other textures. I'm assuming that this is for character customization, to stitch different pieces of face together.

In the fragment (or surf) function, sample your 3 textures and the mask:

fixed4 face = tex2D(_FaceTex, i.uv); // Green channel of the mask
fixed4 eyes = tex2D(_EyeTex, i.uv); // Blue channel of the mask
fixed4 mouth = tex2D(_MouthTex, i.uv); // No mask value (black)
fixed4 mask = tex2D(_MaskTex, i.uv);

Then, you need to blend them together using the mask. Let's assume that whatever black represents in the mask is the background color, and then we interpolate in the other textures.

fixed4 col = lerp(mouth, eyes, mask.b);

Then we can interpolate between the resulting color and our third value:

col = lerp(col, face, mask.g);

You could repeat this once again with the red channel, for a fourth texture. Of course, this assumes that you use pure red, green, or blue in the mask. There are ways to use a more specific color as key too, for instance you can use the absolute of the distance between the mask color and some reference color:

fixed4 eyeMaskColor = (0.5, 0.5, 1, 1);
half t = 1 - saturate(abs(length(mask - eyeMaskColor)));

In this case, t is the lerp factor you use to blend in the texture. The saturate function clamps the value in the range of [0, 1]. If the mask color is the same as eyeMaskColor, then the length of the vector between them is 0 and the statement evaluates to 1.

Upvotes: 1

Related Questions