- Home /
Using a Texture2D as a Normal Map
I'm trying to modify the normal map of a model on the fly in code. I have created a Texture2D and successfully assigned it to the normal map slot ("_BumpMap") on the standard shader but the normal values don't appear to be producing the correct effect. From other references, I thought the correct conversion was:
(r,g,b) = (0.5 + n.x/2, 0.5 + n.y / 2. 0.5 + n.z / 2)
but this looks wrong in the out. The result is too dark, similar to what happens if you using a texture as a normal map without importing it as one. This makes me think that maybe the texture importer does some filtering on the texture first?
The code I am using:
Texture2D normalMap = new Texture2D(width, height);
Color flat = new Color(0.5f, 0.5f, 1.0f);
var pixels = normalMap.GetPixels();
for (int i = 0; i < pixels.Length; i++) {
pixels[i] = flat;
}
normalMap.SetPixels(pixels);
normalMap.Apply();
MeshRenderer mr = GetComponent<MeshRenderer>();
mr.material.SetTexture("_BumpMap", normalMap);
I have the same issue, Whether have you fixed this problem later?
Answer by Wordsonplay · Aug 25, 2015 at 02:46 PM
I found the answer here:
http://answers.unity3d.com/questions/170985/how-does-unity-handle-normal-maps-internally.html
Apparently Unity only stores the x and y components internally, since the z component can be computed from these (assuming it is normalised). They are stored in the alpha and green components respectively:
(r,g,b,a) = (0, 0.5 + v.y / 2, 0, 0.5 + v.x / 2)
Your answer
Follow this Question
Related Questions
Normal map partially visible through another sprite,2D Normal map causing partial transparency 2 Answers
Problem importing normal map texture at runtime 0 Answers
Create Texture2D and assign image to it through a script 1 Answer
Two flat textures interfere with each other when both on z=0 2 Answers
How do you create animated textures with Texture2D.Apply with any regularity? 1 Answer