Skip to content

Instantly share code, notes, and snippets.

@arkms
Created February 1, 2018 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arkms/e312cbe5243c047db124de55187ecaf1 to your computer and use it in GitHub Desktop.
Save arkms/e312cbe5243c047db124de55187ecaf1 to your computer and use it in GitHub Desktop.
Obtener el NormalMap de un Texture2D en runtime
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Basado en: https://forum.unity.com/threads/bumpmap-grayscale-to-normalmap-rgb.5714/
public class TextureToNormalmap : MonoBehaviour
{
//---CODIGO DE EJEMPLO------------------------------
public Texture2D textura;
[Range(10f, 20f)]
public float distortion= 10.0f;
// Use this for initialization
void Start () {
Material mat = GetComponent<Renderer> ().material;
Texture2D Normal = GraytoNormalMap (textura, distortion);
mat.mainTexture = Normal;
}
//---TERMINA CODIGO DE EJEMPLO-----------------------
//Ayuda a clampear y exagerar el efecto
float sCurve(float _x, float _distortion = 10.0f)
{
return 1f / ( 1f + Mathf.Exp(-Mathf.Lerp(5f,15f,_distortion)*(_x-0.5f)));
}
Texture2D GraytoNormalMap(Texture2D t, float _distortion)
{
Texture2D n = new Texture2D(t.width,t.height,TextureFormat.ARGB32,true);
for(int y=1;y<t.width-1;y++)
{
for(int x=1;x<t.height*2-1;x++)
{
float xLeft = t.GetPixel(x-1,y).grayscale;
float xRight = t.GetPixel(x+1,y).grayscale;
float yUp = t.GetPixel(x,y-1).grayscale;
float yDown = t.GetPixel(x,y+1).grayscale;
float xDelta = ((xLeft-xRight)+1)*.5f;
float yDelta = ((yUp-yDown)+1)*.5f;
n.SetPixel(x,y,new Color( Mathf.Clamp01(sCurve(xDelta, distortion)) , Mathf.Clamp01(sCurve(yDelta, distortion)),1f,1.0f));
}
}
n.Apply();
return n;
}
Texture2D NormalmapToGray(Texture2D t)
{
Texture2D n = new Texture2D(t.width,t.height,TextureFormat.ARGB32,true);
Color oldColor = new Color();
Color newColor = new Color();
for (int x=0; x<t.width; x++){
for (int y=0; y<t.height; y++){
oldColor = t.GetPixel(x,y);
newColor.r = oldColor.g;
newColor.b = oldColor.g;
newColor.g = oldColor.g;
newColor.a = oldColor.r;
n.SetPixel(x,y, newColor);
}
}
n.Apply();
return n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment