倆個要點:1 是判斷物體在攝像機的前面 2 是判斷物體的視口座標在(0,0)至(1,1)之間spa
public bool IsInView(Vector3 worldPos) { Transform camTransform = Camera.main.transform; Vector2 viewPos = Camera.main.WorldToViewportPoint(worldPos); Debug.Log("viewPos.x:" + viewPos.x); Debug.Log("viewPos.y:" + viewPos.y); Vector3 dir = (worldPos - camTransform.position).normalized; float dot = Vector3.Dot(camTransform.forward, dir); //判斷物體是否在相機前面 if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1) return true; else return false; } void Update() { if (IsInView(transform.position)) { Debug.Log("目前本物體在攝像機範圍內"); } else { Debug.Log("目前本物體不在攝像機範圍內"); } }