Unity使用程序生成Texture2D并创建Sprite,制作渐变背景的效果

发表于2019-01-28
评论0 7.5k浏览
上篇文章中介绍过如何使用shader实现一个渐变的背景效果这里再介绍一种方法,在脚本中动态创建Texture2D并生成Sprite。

首先创建脚本,命名为ScriptTexture.

声明一个引用:
 SpriteRenderer sr;

然后在初始化中创建我们需要的物体:
	void Start () {
        GameObject obj = new GameObject("spriet");
        sr = obj.AddComponent<SpriteRenderer>();
	}

这里首先创意一个gameobject,然后给这个物体添加一个SpriteRenderer脚本并保存到我们之前的全局变量中。

接下来生成纹理:
    void GenerateSprite () {
        Texture2D t = new Texture2D(256, 512);
        for (int w = 0; w < width; w++){
            for (int h = 0; h < height; h ++){
                t.SetPixel(w,h,Color.yellow);
            }
        }
        t.Apply();
        Sprite pic = Sprite.Create(t, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
        sr.sprite = pic;
	}

这里我们首先创建一个Texture2D,并指定宽高,接下来遍历Texture2D的每一像素点并赋值。

然后使用Texture2D生成一个Sprite并赋值给之前创建的SpriteRenderer。

最后在start中调用此方法,再把脚本挂到游戏摄像机上,运行场景看下效果:

场景中出现了我们的sprite,接下来我们按照之前讲的shader中同样的方法来给精灵添加一个渐变的效果,直接给出修改后的完整代码:
public class ScriptTexture : MonoBehaviour
{
    public Color color1 = Color.green;
    public Color color2 = Color.blue;
    public int width = 640, height = 960;
    SpriteRenderer sr;
    // Use this for initialization
    void Start()
    {
        GameObject obj = new GameObject("spriet");
        sr = obj.AddComponent<SpriteRenderer>();
        GenerateSprite();
    }
    // Update is called once per frame
    void GenerateSprite()
    {
        Texture2D t = new Texture2D(width, height);
        for (int w = 0; w < width; w++)
        {
            for (int h = 0; h < height; h++)
            {
                float wrate = (float)w / (float)width;
                float hrate = (float)h / (float)height;
                float bezieratVal = GetBezierat(0, 0.5f, 0.5f, 1, hrate);
                float dis = Vector2.Distance(new Vector2(0.5f, 0.5f),new Vector2(wrate,hrate));
                dis = 1 - GetBezierat(0, 0, 1, 2, dis) * 0.6f;  
                Color c = new Color();
                c.r = Mathf.Lerp(color1.r, color2.r, bezieratVal) * dis;
                c.g = Mathf.Lerp(color1.g, color2.g, bezieratVal) * dis;
                c.b = Mathf.Lerp(color1.b, color2.b, bezieratVal) * dis;
                c.a = 255;
                t.SetPixel(w, h,c);
            }
        }
        t.Apply();
        Sprite pic = Sprite.Create(t, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
        sr.sprite = pic;
    }
    float GetBezierat(float a, float b, float c, float d, float t)
    {
        return (Mathf.Pow(1 - t, 3) * a +
                3 * t * (Mathf.Pow(1 - t, 2)) * b +
                3 * Mathf.Pow(t, 2) * (1 - t) * c +
                Mathf.Pow(t, 3) * d);
    }
}

看下最终效果:

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引