Last active
August 29, 2015 14:10
-
-
Save westhillapps/61d165a794e1ca9bf201 to your computer and use it in GitHub Desktop.
Planeのアスペクト比を固定したままスケーリングする
This file contains hidden or 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; | |
[ExecuteInEditMode] | |
public class FixPlaneAspectRatio : MonoBehaviour | |
{ | |
enum HEIGHT_PARAM | |
{ | |
Y, | |
Z, | |
} | |
// Planeに適用しているテクスチャのサイズ | |
[SerializeField] | |
int originalWidth; | |
[SerializeField] | |
int originalHeight; | |
// 高さを反映する向き | |
[SerializeField] | |
HEIGHT_PARAM toHeightParam = HEIGHT_PARAM.Z; | |
// Updateで適用する | |
[SerializeField] | |
bool fixOnUpdate; | |
Vector3 lastScale = Vector3.zero; | |
Vector3 newScale = Vector3.zero; | |
// Transformキャッシュ | |
Transform myTransform; | |
new Transform transform { | |
get { | |
return myTransform != null ? myTransform : (myTransform = GetComponent<Transform> ()); | |
} | |
} | |
void Awake () | |
{ | |
lastScale = transform.localScale; | |
} | |
void Update () | |
{ | |
#if UNITY_EDITOR | |
if (Application.isPlaying == false) { | |
FixAspectRatio (); | |
return; | |
} | |
#endif | |
if (fixOnUpdate) { | |
FixAspectRatio (); | |
} | |
} | |
void FixAspectRatio () | |
{ | |
if (originalWidth <= 0 || originalHeight <= 0) { | |
return; | |
} | |
bool changeX; | |
if (lastScale.x != transform.localScale.x) { | |
changeX = true; | |
} else if (lastScale.z != transform.localScale.z) { | |
changeX = false; | |
} else { | |
return; | |
} | |
if (changeX) { | |
float ratio = transform.localScale.x / (float)originalWidth; | |
if (toHeightParam == HEIGHT_PARAM.Y) { | |
newScale.Set (transform.localScale.x, (float)originalHeight * ratio, transform.localScale.z); | |
} else { | |
newScale.Set (transform.localScale.x, transform.localScale.y, (float)originalHeight * ratio); | |
} | |
} else { | |
float ratio = toHeightParam == HEIGHT_PARAM.Y ? transform.localScale.y / (float)originalHeight : transform.localScale.z / (float)originalHeight; | |
newScale.Set ((float)originalWidth * ratio, transform.localScale.y, transform.localScale.z); | |
} | |
transform.localScale = newScale; | |
lastScale = transform.localScale; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment