Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active April 26, 2016 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/c0e2c4bcdb03e6ddf8ecb2ad0b35ced3 to your computer and use it in GitHub Desktop.
Save tsubaki/c0e2c4bcdb03e6ddf8ecb2ad0b35ced3 to your computer and use it in GitHub Desktop.
UIが追跡する
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