Skip to content

Instantly share code, notes, and snippets.

@JT5D
Forked from unitycoder/PlanarUVMap.cs
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save JT5D/477d68b3b265ab97d78c to your computer and use it in GitHub Desktop.

Select an option

Save JT5D/477d68b3b265ab97d78c to your computer and use it in GitHub Desktop.
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