using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetPixel : MonoBehaviour
{
public RenderTexture rendTex;
private Texture2D sourceTex;
public GameObject prefab;
public float offset = 1.2f;
public float prefabScale = 5.0f;
private int _width;
private int _height;
private Color[] pix;
private List<GameObject> list;
private List<Renderer> rendlist;
private List<Transform> transformlist;
private MaterialPropertyBlock properties;
void Start()
{
sourceTex = GetRTPixels(rendTex);
//소스 텍스트 크기
_width = sourceTex.width;
_height = sourceTex.height;
//픽셀 색깔 저장하기
pix = sourceTex.GetPixels(0, 0, _width, _height);
//리스트 생성
list = new List<GameObject>();
rendlist = new List<Renderer>();
transformlist = new List<Transform>();
properties = new MaterialPropertyBlock();
//픽셀 큐브 생성
for (int w = 0; w < _width; w++)
{
for (int h = 0; h < _height; h++)
{
GameObject obj = Instantiate(prefab, new Vector3(w * offset, 0, h * offset), Quaternion.identity) as GameObject;
list.Add(obj);
transformlist.Add(obj.transform);
Renderer rend = obj.GetComponent<Renderer>();
rendlist.Add(rend);
obj.transform.SetParent(transform);
}
}
transform.rotation = Quaternion.Euler(180, -90, -90); //보드 회전하기
}
private void Update()
{
sourceTex = GetRTPixels(rendTex); //실시간으로 texture받아오기
pix = sourceTex.GetPixels(0, 0, _width, _height); //pixel 받아오기
//픽셀 색상 적용
for (int i = 0; i < _width * _height; i++)
{
properties.SetColor("_Color", pix[i]);//gpuInstancing pixel Color값 받아오기
rendlist[i].SetPropertyBlock(properties); //gpuInstancing 사용 Color값 적용
}
//pixel 애니메이션
for (int i = 0; i < _width * _height; i++)
{
//화이트 제외 -> 사용하려면 아래 else로 묶어주기
//if(pix[i].r > .7f && pix[i].g > .7f && pix[i].b > .7f)
//{
// transformlist[i].localScale =
// new Vector3(1, Mathf.Lerp(list[i].transform.localScale.y, 0.1f, Time.deltaTime * 5.0f), 1);
//}
float color = pix[i].r + pix[i].g + pix[i].b;
//색상 값 pingpong (균일)
transformlist[i].localScale =
new Vector3(1, Mathf.PingPong(color * Time.time + .01f, color * prefabScale + 0.01f), 1);
//색상 값 pingpong (비균일)
//transformlist[i].localScale =
//new Vector3(1, Mathf.PingPong(Time.time + .01f, color * prefabScale + 0.01f), 1);
//속도 값 pingpong
//transformlist[i].localScale =
//new Vector3(1, Mathf.PingPong(Time.time + color + 0.01f, prefabScale), 1);
//색상 값 lerp - 색상 변형 영향 x
//transformlist[i].localScale =
//new Vector3(1, Mathf.Lerp(list[i].transform.localScale.y, (color + 0.01f) * prefabScale, Time.deltaTime * 5.0f), 1);
}
}
//renderTexture -> Texture2D로 전환 함수
static public Texture2D GetRTPixels(RenderTexture rt)
{
RenderTexture currentActiveRT = RenderTexture.active;
RenderTexture.active = rt;
Texture2D tex = new Texture2D(rt.width, rt.height);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
RenderTexture.active = currentActiveRT;
return tex;
}
}