LoginSignup
2
2

More than 5 years have passed since last update.

UguiでCameraに写っているかどうか判定する

Last updated at Posted at 2018-11-29

カメラに写っているかの判定方法は

【Unity】オブジェクトが画面外かどうかを判定する方法(まとめ)

の記事が詳しいのですが、微妙にCanvasのImageとかの場合どうすればいいのかというとあまりよいのがない。
Renderer.isVisibleやOnBecameVisible、OnBecameInVisibleやOnWillRenderObjectとかを使うのはMeshRendererとかが必要なのでuguiで使うにはびみょい。

Camera.ViewportToWorldPointを使うとよさそうだが普通にやったらGameObjectの位置になってしまうのでRectの範囲をとりたいわけです。

というわけで以下。

testVisibleCheck.cs
using UnityEngine;

public class testVisibleCheck : MonoBehaviour {

    //Uguiを表示してるカメラを貼り付ける
    [SerializeField] private Camera camera;

    private RectTransform _target;

    private Rect rect = new Rect(0, 0, 1, 1);

    public bool isVisible;

    void Start()
    {
        _target = this.GetComponent<RectTransform>();
    }

    void Update()
    {
        isVisible = rect.Contains(camera.WorldToViewportPoint(_target.transform.position + (Vector3)(_target.rect.min * _target.lossyScale.x))) ||
                   rect.Contains(camera.WorldToViewportPoint(_target.transform.position + (Vector3)(_target.rect.max * _target.lossyScale.x)));
    }

}

Canvas以下にあるGameObjectにImageでも付けてみて移動してみてください。見えなくなった(画面外)でisVisibleがfalseになります。

ただこれ、親のCanvasのrendermode設定がScreen Space Overlayだとちゃんと動きません。

テストだからUpdateに入れてるけど、毎フレームでやると重くなるかもしれないので値変更時にやるとかいいかも。uniRxだと簡単ですね。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2