So when I trying to make a “worms” style destructible 2d terrain, I changed default sprite shader a bit to let it recieve a alpha map, and then I can edit the alpha map pixel wise at runtime to make part of the original texture transparent.
The manipulation of the alpha map texture is done by Texture2D.setPixels
By my understanding, Texture2D.getPixels() will return a color array that in forms like:
08 09 10 11
04 05 06 07
00 01 02 03
Am I correct?
The shader is basicly the default Sprite shader except the frag:
fixed4 frag(v2f IN) : COLOR
{
return tex2D(_MainTex, IN.texcoord) * tex2D(_AlphaMask, IN.texcoord) * IN.color;
}
This is the code I use to initialize the alpha map texture:
Texture2D t2d;
Color32[] colorArray;
int h;
int w;
// Use this for initialization
void Start()
{
Texture2D t = GetComponent<SpriteRenderer>().sprite.texture;
w = t.width;
h = t.height;
t2d = new Texture2D(w, h);
colorArray = new Color32[t.width * t.height];
for (int i = 0; i < colorArray.Length; i++)
{
colorArray[i] = Color.red * 255;
}
t2d.SetPixels32(colorArray);
t2d.Apply();
renderer.material.SetTexture("_AlphaMask", t2d);
}
This the code I use to test setPixels:
public void draw()
{
//cut top
for (int i = colorArray.Length * 3 / 4; i < colorArray.Length; i++)
{
colorArray[i].a = 0;
}
//cut bottom
for (int i = 0; i < colorArray.Length / 4; i++)
{
colorArray[i].a = 0;
}
t2d.SetPixels32(colorArray);
t2d.Apply();
}
this is the original texture:

this is the result after start before draw:

this is the result of only run cut top:

this is the result of only run cut bottom:

this is the result of run both cut top and cut bottom:

If you look closely at the result of cut top only and cut bottom only, you will see both of them have a line of pixels remain unchanged, and those lines disappeared in cut both. SInce the line is red, the shader should works correctly, and I have no clue what cause this weird issue, please help.
Another question:is there a way to change the texture of a Sprite? Sprite.texture is readonly
