【转】Unity3d 检测物体在不在摄像机照射范围内

转自:http://www.cnblogs.com/AdvancePikachu/p/6733620.html

[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. /// <summary>  
  5. /// 将脚本挂在摄像机观察的物体上  物体必须带有Render  
  6. /// </summary>  
  7. public class PlayerView : MonoBehaviour {  
  8.   
  9.     bool isRendering;    
  10.     float curtTime = 0f;  
  11.     float lastTime = 0f;  
  12.   
  13.     void OnWillRenderObject()  
  14.     {  
  15.         curtTime = Time.time;  
  16.     }  
  17.     public bool IsInView(Vector3 worldPos)  
  18.     {  
  19.         Transform camTransform = Camera.main.transform;  
  20.         Vector2 viewPos = Camera.main.WorldToViewportPoint(worldPos);  
  21.         Vector3 dir = (worldPos - camTransform.position).normalized;  
  22.         float dot = Vector3.Dot(camTransform.forward, dir);     //判断物体是否在相机前面  
  23.   
  24.         if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1)  
  25.             return true;  
  26.         else  
  27.             return false;  
  28.     }  
  29.   
  30.     void Update()  
  31.     {  
  32.         Vector2 vec2 = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);  
  33.           
  34.         if (IsInView(transform.position))     
  35.         {  
  36.             Debug.Log("目前本物体在摄像机范围内");  
  37.         }  
  38.         else  
  39.         {  
  40.             Debug.Log("目前本物体不在摄像机范围内");    
  41.         }  
  42.     }  
  43. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值