본문 바로가기
개발/코드

Unity)코드) Camera View 안에 있는 Object 구분하기

by 테샤르 2021. 5. 11.

Camera View 안에 있는 Object 구분하기

Unity에서 Camera의 View안에 포함되어있는 오브젝트를 판단해야 할 상황에서 사용이 가능한 코드이다.

간단하게 설명하면 해당 오브젝트들이 카메라안에 있는지 여부를 판단해 준다.

코드를 보면 간단하게 체크해야하는 오브젝트를 Camera의 ViewPoint로

변환 값이 0~1 사이에 포함되어있는지 판단하는 코드이다. distance(z) 도 체크가 잘된다.

 

반응형
public class CameraViewObject : MonoBehaviour
{
    [SerializeField]
    private List<GameObject> findList = null;

    private Camera cam;

    void Start()
    {
        cam = UnityEngine.Camera.main;
    }

    // Update is called once per frame
    void Update()
    {

        for (int i = 0; i < findList.Count; i++){
            Vector3 viewPos = cam.WorldToViewportPoint(findList[i].transform.position);
            if (viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0)
            {
               Debug.Log($" Camer in Object : {findList[i].name}");
            }
        }
    }

}

 

스택 오버플로우 : [링크]

 

Unity-How do I check if an object is seen by the Main Camera

I'm doing this thing where an object is moving on a plane, and the camera is in the center of it. I got it so the camera rotates along with the mouse, and when the main camera sees the game object,...

stackoverflow.com

 

★☆

 

반응형

댓글