創建一個腳本 附加到一個游戲體上
using UnityEngine;
using System.Collections;
public class ProceduralTexture : MonoBehaviour
{
#region Public Variables
//紋理的寬高
public int widthHeight = 512;
//程序生成的紋理
public Texture2D generaterdTexture;
#endregion
#region Private Variables
private Material currentMaterial;
private Vector2 centerPosition;
#endregion
// Use this for initialization
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);
generaterdTexture = GenerateParabola();
//設置紋理
currentMaterial.SetTexture("_MainTex",generaterdTexture);
}
}
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++)
{
//Get the distance from the center of the texture to
//our currently selected pixel
Vector2 currentPosition = new Vector2(x, y);
//當前像素點到中心點的距離 / 紋理寬高的一半
float pixelDistance = Vector2.Distance(currentPosition, centerPixelPosition) / (widthHeight * 0.5f);
// Mathf.Abs : 取絕對值 Mathf.Clamp 0-1
pixelDistance = Mathf.Abs(1 - Mathf.Clamp(pixelDistance, 0f, 1f));
pixelDistance = (Mathf.Sin(pixelDistance * 30.0f) * pixelDistance);
//you can also do some more advanced vector calculations to achieve
//other types of data about the model itself and its uvs and
//pixels
//以中心為原點 獲取到當前像素點的向量
Vector2 pixelDirection = centerPixelPosition - currentPosition;
pixelDirection.Normalize();
//當前像素點向量 和 上左右三個方向的向量之間的夾角
float rightDirection = Vector2.Angle(pixelDirection, Vector3.right) / 360;
float leftDirection = Vector2.Angle(pixelDirection, Vector3.left) / 360;
float upDirection = Vector2.Angle(pixelDirection, Vector3.up) / 360;
//確保像素點的顏色值在 (0,1) 之間
//Create a new color value based off of our
//Color pixelColor = new Color(Mathf.Max(0.0f, rightDirection),Mathf.Max(0.0f, leftDirection), Mathf.Max(0.0f,upDirection), 1f);
Color pixelColor = new Color(pixelDistance, pixelDistance, pixelDistance, 1.0f);
//Color pixelColor = new Color(rightDirection, leftDirection, upDirection, 1.0f);
proceduralTexture.SetPixel(x, y, pixelColor);
//將中間的像素點設置成紅色
if (x == widthHeight / 2 || y == widthHeight / 2)
{
Color middlePixelColor = new Color(1, 0, 0, 1.0f);
proceduralTexture.SetPixel(x, y, middlePixelColor);
}
}
}
//Finally force the application of the new pixels to the texture
proceduralTexture.Apply();
//return the texture to the main program.
return proceduralTexture;
}
// Update is called once per frame
void Update () {
}
}