动态创建纹理贴图

作者:追风剑情 发布于:2016-1-9 12:03 分类:Shader

using UnityEngine;
using System.Collections;

public class GenerateTexture : MonoBehaviour {

	public int widthHeight = 512;
	public Texture2D generatedTexture;

	private Material currentMaterial;
	private Vector2 centerPosition;

	void Start () {
		if (!currentMaterial) {
			currentMaterial = transform.renderer.sharedMaterial;
			if (!currentMaterial)
				Debug.LogWarning("Cannot find a material on: "+transform.name);
		}

		if (currentMaterial) {
			centerPosition = new Vector2(0.5f, 0.5f);
			generatedTexture = GenerateParabola();
			//动态设置贴图
			currentMaterial.SetTexture("_MainTex", generatedTexture);
		}
	}

	// 创建Texture2D
	private Texture2D GenerateParabola()
	{
		Texture2D proceduralTexture = new Texture2D (widthHeight, widthHeight);
		//贴图中心点坐标
		Vector2 centerPixelPosition = centerPosition * widthHeight;

		for (int x = 0; x < widthHeight; x++) {
			for (int y = 0; y < widthHeight; y++) {
				Vector2 currentPosition = new Vector2(x, y);
				//计算当前坐标与中心点坐标距离并映射到0~1范围。
				float pixelDistance = Vector2.Distance(currentPosition, centerPosition)/(widthHeight*0.5f);
				//对颜色值取反
				pixelDistance = Mathf.Abs(1-Mathf.Clamp(pixelDistance, 0f, 1f));
				Color pixelColor = new Color(pixelDistance, pixelDistance, pixelDistance, 1.0f);
				proceduralTexture.SetPixel(x, y, pixelColor);
			}
		}
		//应用新像素值
		proceduralTexture.Apply();
		return proceduralTexture;
	}
}

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号