カメラの範囲内のUnityオブジェクト検出視野



Unity Object Detection Field View Range Camera



要約:オリジナル、出典を示してください: http://www.cnblogs.com/AdvancePikachu/p/6733620.html

要求する:



NPCの同様の血、NPCでのカメラの表示、採血、および頭がNPCに残っている場合。

開始:



オンラインで情報を見つけて、次のコードを記述します。

public RectTransform rectBloodPos void Update () { this.gameObject.transform.Translate (Input.GetAxis ('Horizontal') * 10 * Time.deltaTime, 0, 0) this.gameObject.transform.Translate (0, 0, Input.GetAxis ('Vertical') * 10 * Time.deltaTime) Vector2 vec2 = Camera.main.WorldToScreenPoint (this.gameObject.transform.position) rectBloodPos.anchoredPosition = new Vector2 (vec2.x - Screen.width / 2 + 0, vec2.y - Screen.height / 2 + 60) }

レンダリングを実現する:



しかし、次に示すように、カメラがオブジェクトの反対側を向いている場合、次のことがわかりました。

一体何、実際には目とUI、そして後で改善するための研究:

 1 bool isRendering  2 float curtTime=0f  3 float lastTime=0f  4  5 void OnWillRenderObject()  6  {  7 curtTime = Time.time  8  }  9 10 void Update () 11  { 12 isRendering = curtTime != lastTime?true:false 13 14 Vector2 vec2 = Camera.main.WorldToScreenPoint (this.gameObject.transform.position) 15 if (isRendering) 16  { 17 rectBloodPos.gameObject.SetActive (true) 18 rectBloodPos.anchoredPosition = new Vector2 (vec2.x - Screen.width / 2 + 0, vec2.y - Screen.height / 2 + 60) 19  } 20 else 21 rectBloodPos.gameObject.SetActive (false) 22 23 lastTime = curtTime 24 25 }

このメソッドの原則は、カメラの範囲と、オブジェクト上のRenderコンポーネントがトリガーされて、UIを描画するときに、スクリプトオブジェクトがハングすることです。

この方法は便利ですが、ボディが多すぎるためにパフォーマンスに影響するため、再び改善されました。

 1 public bool IsInView(Vector3 worldPos)  2  {  3 Transform camTransform = Camera.main.transform  4 Vector2 viewPos = Camera.main.WorldToViewportPoint (worldPos)  5 Vector3 dir = (worldPos - camTransform.position).normalized  6 float dot = Vector3.Dot (camTransform.forward, dir)//Determining whether the object in front of the camera  7  8 if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1)  9 return true 10 else 11 return false 12  } 13 14 void Update () 15  { 16 Vector2 vec2 = Camera.main.WorldToScreenPoint (this.gameObject.transform.position) 17 18 if (IsInView (transform.position)) 19  { 20 rectBloodPos.gameObject.SetActive (true) 21 rectBloodPos.anchoredPosition = new Vector2 (vec2.x - Screen.width / 2 + 0, vec2.y - Screen.height / 2 + 60) 22  } 23 else 24 rectBloodPos.gameObject.SetActive (false) 25 }

このメソッドはVector3です。Dot()メソッドは、UIかどうかを判断するために、カメラとオブジェクトの方向、および前面と背面を決定します。

従うべきNPCの血のより完全な実現。

小さなパートナーがより良い方法を持っているなら、私たちはああを共有することを忘れないでください! ! !