using UnityEngine;
[ExecuteInEditMode]//编辑模式下执行
public class BeRivet : MonoBehaviour
{
public enum EAlign { TopLeft, Top, TopRight, Left, Center, Right, BottomLeft, Bottom, BottomRight }
public string Prefix = "r_";
public EAlign Side = EAlign.Center;
public Vector2 Size = new Vector2(50, 50);
const string TexturePath = "Texture/attach/object/thumbtack";
UIRoot m_root;
Camera m_camera;
UITexture m_texture;
void Start()
{
m_root = FindObjectOfType<UIRoot>();
m_camera = m_root.transform.FindChild("Camera").GetComponent<Camera>();
gameObject.AddMissingComponent<UITexture>();
m_texture = GetComponent<UITexture>();
m_texture.mainTexture = Resources.Load<Texture>(TexturePath);
m_texture.width = Mathf.FloorToInt(Size.x);
m_texture.height = Mathf.FloorToInt(Size.y);
}
void Update()
{
positionAdjust(Side, m_texture.width, m_texture.height);
}
void positionAdjust(EAlign side, float width, float height)
{
gameObject.name = Prefix + Side;
var pixelOffset = new Vector2();
switch (side)
{
case EAlign.TopLeft:
case EAlign.Left:
case EAlign.BottomLeft:
pixelOffset.x = (width / 2);
break;
case EAlign.TopRight:
case EAlign.Right:
case EAlign.BottomRight:
pixelOffset.x = -(width / 2);
break;
default:
pixelOffset.x = 0;
break;
}
switch (side)
{
case EAlign.BottomLeft:
case EAlign.Bottom:
case EAlign.BottomRight:
pixelOffset.y = (height / 2);
break;
case EAlign.TopLeft:
case EAlign.Top:
case EAlign.TopRight:
pixelOffset.y = -(height / 2);
break;
default:
pixelOffset.y = 0;
break;
}
alignToScreen(side, m_camera, transform, pixelOffset);
}
static void alignToScreen(EAlign side, Camera uiCamera, Transform trans, Vector2 pixelOffset = default(Vector2), Vector2 relativeOffset = default(Vector2))
{
var rect = uiCamera.pixelRect;
var cx = (rect.xMin + rect.xMax) * 0.5f;
var cy = (rect.yMin + rect.yMax) * 0.5f;
var v = new Vector3(cx, cy, 0f);
if (side != EAlign.Center)
{
switch (side)
{
case EAlign.TopRight:
case EAlign.Right:
case EAlign.BottomRight:
v.x = rect.xMax;
break;
case EAlign.Top:
case EAlign.Center:
case EAlign.Bottom:
v.x = cx;
break;
default:
v.x = rect.xMin;
break;
}
switch (side)
{
case EAlign.TopLeft:
case EAlign.Top:
case EAlign.TopRight:
v.y = rect.yMax;
break;
case EAlign.Left:
case EAlign.Center:
case EAlign.Right:
v.y = cy;
break;
default:
v.y = rect.yMin;
break;
}
}
v.x += pixelOffset.x + relativeOffset.x * rect.width;
v.y += pixelOffset.y + relativeOffset.y * rect.height;
if (uiCamera.orthographic)
{
v.x = Mathf.Round(v.x);
v.y = Mathf.Round(v.y);
}
v.z = uiCamera.WorldToScreenPoint(trans.position).z;
v = uiCamera.ScreenToWorldPoint(v);
if (uiCamera.orthographic && trans.parent != default(Transform))
{
v = trans.parent.InverseTransformPoint(v);
v.x = Mathf.RoundToInt(v.x);
v.y = Mathf.RoundToInt(v.y);
if (trans.localPosition != v) trans.localPosition = v;
}
else if (trans.position != v)
{
trans.position = v;
}
}
}
BeRivet.cs
最新推荐文章于 2024-01-24 22:33:04 发布