Last active
August 29, 2015 14:19
-
-
Save unitycoder/993f7b3d46469a792715 to your computer and use it in GitHub Desktop.
Set UV map to Planar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
// modified from : http://docs.unity3d.com/ScriptReference/Mesh-uv.html | |
public class PlanarUVMap : MonoBehaviour { | |
public bool flipX=false; | |
void Start() | |
{ | |
UsePlanarUV(); | |
} | |
void UsePlanarUV() | |
{ | |
Mesh mesh = GetComponent<MeshFilter>().mesh; | |
Vector3[] vertices = mesh.vertices; | |
Vector2[] uvs = new Vector2[vertices.Length]; | |
Vector2 min = new Vector2(Mathf.Infinity, Mathf.Infinity); | |
Vector2 max = new Vector2(Mathf.NegativeInfinity,Mathf.NegativeInfinity); | |
for (int i=0; i < uvs.Length; i++) | |
{ | |
min = new Vector2( Mathf.Min(min.x,vertices[i].x), Mathf.Min(min.y,vertices[i].z)); | |
max = new Vector2( Mathf.Max(max.x,vertices[i].x), Mathf.Max(max.y,vertices[i].z)); | |
} | |
float fixScaleX = 16; // temporary fix for X uv map | |
for (int i=0; i < uvs.Length; i++) | |
{ | |
float uvx = Remap(vertices[i].x,min.x,max.x,0,1)*fixScaleX; | |
float uvy = Remap(vertices[i].z,min.y,max.y,0,1); | |
uvs[i] = new Vector2(flipX?1-uvx:uvx,uvy); | |
} | |
mesh.uv = uvs; | |
} | |
// remap value from range to another range | |
float Remap(float current, float sourceRangeFrom, float sourceRangeTo, float targetRangeFrom, float targetRangeTo) | |
{ | |
return targetRangeFrom + (current-sourceRangeFrom)*(targetRangeTo-targetRangeFrom)/(sourceRangeTo-sourceRangeFrom); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment