//-------------------------------------------- // NGUI: HUD Text // Copyright © 2012 Tasharen Entertainment //-------------------------------------------- using UnityEngine; /// /// Attaching this script to an object will make it visibly follow another object, even if the two are using different cameras to draw them. /// public class UIFollowTarget : MonoBehaviour { public delegate void OnVisibilityChange (bool isVisible); /// /// Callback triggered every time the object becomes visible or invisible. /// public OnVisibilityChange onChange; /// /// 3D target that this object will be positioned above. /// public Transform target; /// /// UI 위치 오프셋, z는 0 /// public Vector3 offSet; /// /// Game camera to use. /// public Camera gameCamera; /// /// UI camera to use. /// public Camera uiCamera; /// /// Whether the children will be disabled when this object is no longer visible. /// public bool disableIfInvisible = true; /// /// Destroy the game object when target disappears. /// public bool destroyWithTarget = true; Transform mTrans; int mIsVisible = -1; /// /// Whether the target is currently visible or not. /// public bool isVisible { get { return mIsVisible == 1; } } /// /// Cache the transform; /// void Awake () { mTrans = transform; } /// /// Find both the UI camera and the game camera so they can be used for the position calculations /// void Start() { if (target) { if (gameCamera == null) gameCamera = NGUITools.FindCameraForLayer(target.gameObject.layer); if (uiCamera == null) uiCamera = NGUITools.FindCameraForLayer(gameObject.layer); Update(); } else { if (destroyWithTarget) Destroy(gameObject); else enabled = false; } } /// /// Update the position of the HUD object every frame such that is position correctly over top of its real world object. /// void Update () { if (target && uiCamera != null) { Vector3 pos = gameCamera.WorldToViewportPoint(target.position); // Determine the visibility and the target alpha int isVisible = (gameCamera.orthographic || pos.z > 0f) && (pos.x > 0f && pos.x < 1f && pos.y > 0f && pos.y < 1f) ? 1 : 0; bool vis = (isVisible == 1); // If visible, update the position if (vis) { pos = uiCamera.ViewportToWorldPoint(pos); if (mTrans.parent != null) pos = mTrans.parent.InverseTransformPoint(pos); //pos.x = Mathf.RoundToInt(pos.x); //pos.y = Mathf.RoundToInt(pos.y); pos.z = 0f; mTrans.localPosition = pos + offSet; } // Update the visibility flag if (mIsVisible != isVisible) { mIsVisible = isVisible; gameObject.SetActive(vis); // Inform the listener if (onChange != null) onChange(vis); } } else { if (destroyWithTarget) Destroy(gameObject); else gameObject.SetActive(false); } } }