# 実現したいこと
Unityで戦闘機ゲームを製作していて、近くの敵をロックオンするスクリプトを作ったのですが、
敵が後ろにいる場合でもロックオンされてしまいます。
自分と敵のZ座標をひいて前後を取得しようとしたのですが、方向が変わると後ろにいてもロックオンしてしまいます。
Unityで他のオブジェクトが自分の前か後ろか取得する正しい方法はあるのでしょうか...
どなたかご教授いただければ幸いです。
C#
1using UnityEngine; 2using UnityEngine.UI; 3using System.Collections; 4 5public class rader : MonoBehaviour 6{ 7 private GameObject nearObj; 8 private float searchTime = 0; 9 public GameObject homing; 10 public GameObject distext; 11 public GameObject gunsight; 12 public Vector3 enemyv3; 13 public Vector3 tfz; 14 public float gapz; 15 // Use this for initialization 16 void Start() 17 { 18 nearObj = serchTag(gameObject, "Player"); 19 } 20 21 // Update is called once per frame 22 void Update() 23 { 24 searchTime += Time.deltaTime; 25 26 if (searchTime >= 0.1f) 27 { 28 nearObj = serchTag(gameObject, "enemy"); 29 30 searchTime = 0; 31 } 32 33 34 } 35 36 37 GameObject serchTag(GameObject nowObj, string tagName) 38 { 39 float tmpDis = 0; 40 float nearDis = 0; 41 GameObject targetObj = null; 42 Text dist = distext.GetComponent<Text>(); 43 44 foreach (GameObject obs in GameObject.FindGameObjectsWithTag(tagName)) 45 { 46 47 tmpDis = Vector3.Distance(obs.transform.position, nowObj.transform.position); 48 49 50 if (nearDis == 0 || nearDis > tmpDis && nearDis <= 1000) 51 { 52 nearDis = tmpDis; 53 targetObj = obs; 54 enemyv3 = obs.transform.position; 55 tfz = transform.InverseTransformDirection(enemyv3); 56 gapz = tfz.z - this.transform.position.z; 57 58 if (nearDis <= 500 && gapz <= 1) 59 { 60 homing = obs; 61 string str = nearDis.ToString("N0"); 62 dist.text = str; 63 gunsight.SetActive(true); 64 } 65 else 66 { 67 gunsight.SetActive(false); 68 } 69 70 } 71 72 } 73 74 75 76 return targetObj; 77 78 } 79}
あなたの回答
tips
プレビュー