Last active
April 26, 2016 15:14
-
-
Save tsubaki/c0e2c4bcdb03e6ddf8ecb2ad0b35ced3 to your computer and use it in GitHub Desktop.
UIが追跡する
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 UnityEngine.UI; | |
public class InOutTest : MonoBehaviour { | |
[SerializeField] Transform target; | |
[SerializeField] Camera targetCamera; | |
[SerializeField] Image icon; | |
private Rect rect = new Rect(0, 0, 1, 1); | |
private Rect canvasRect; | |
void Start() | |
{ | |
// UIがはみ出ないようにする | |
canvasRect = ((RectTransform)icon.canvas.transform).rect; | |
canvasRect.Set( | |
canvasRect.x + icon.rectTransform.rect.width * 0.5f, | |
canvasRect.y + icon.rectTransform.rect.height * 0.5f, | |
canvasRect.width - icon.rectTransform.rect.width, | |
canvasRect.height - icon.rectTransform.rect.height | |
); | |
} | |
void Update () | |
{ | |
var viewport = targetCamera.WorldToViewportPoint(target.position); | |
if (rect.Contains(viewport)) | |
{ | |
icon.enabled = false; | |
}else | |
{ | |
icon.enabled = true; | |
// 画面内で対象を追跡 | |
viewport.x = Mathf.Clamp01(viewport.x); | |
viewport.y = Mathf.Clamp01(viewport.y); | |
icon.rectTransform.anchoredPosition = Rect.NormalizedToPoint(canvasRect, viewport); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment