【常用】查找子物体
using UnityEngine;
using System.Collections;
using System.Collections.Generic;/// <summary>
/// 變換組件助手類
/// </summary>
public class TransformHelper
{/// <summary>/// 未知層級(jí)關(guān)系,根據(jù)名稱查找后代物體。/// </summary>/// <param name="parentTF">父物體變換組件</param>/// <param name="childName">需要檢索的子物體名稱</param>/// <returns></returns>public static Transform FindChild(Transform parentTF, string childName){//遞歸:將問題轉(zhuǎn)移給范圍縮小的同類子問題//作用:將復(fù)雜的問題簡(jiǎn)單化。//步驟:找兒子 如果沒有 轉(zhuǎn)移給兒子//1.找兒子Transform childTF = parentTF.Find(childName);//如果查找到 則返回子物體變換組件 退出方法if (childTF != null) return childTF;//2.如果沒有for (int i = 0; i < parentTF.childCount; i++){//3.轉(zhuǎn)移給兒子childTF = FindChild(parentTF.GetChild(i), childName);if (childTF != null) return childTF;}return null;/*3! 階乘 3 * 2 * 1*/}/// <summary>/// 逐漸注視目標(biāo)點(diǎn)旋轉(zhuǎn)/// </summary>/// <param name="targetTF">變換組件</param>/// <param name="targetPos">目標(biāo)點(diǎn)</param>/// <param name="rotateSpeed">旋轉(zhuǎn)速度</param>public static void LookPostion(Transform targetTF, Vector3 targetPos, float rotateSpeed){Vector3 dir = targetPos - targetTF.position;LookDirection(targetTF, dir, rotateSpeed);}/// <summary>/// 逐漸注視目標(biāo)方向旋轉(zhuǎn)/// </summary>/// <param name="targetTF">變換組件</param>/// <param name="targetDir">目標(biāo)方向</param>/// <param name="rotateSpeed">旋轉(zhuǎn)速度</param>public static void LookDirection(Transform targetTF, Vector3 targetDir, float rotateSpeed){//如果需要注視零方向if (targetDir == Vector3.zero) return;//transform.LookAt(目標(biāo)點(diǎn)); 一幀旋轉(zhuǎn)到位Quaternion dir = Quaternion.LookRotation(targetDir);targetTF.rotation = Quaternion.Lerp(targetTF.rotation, dir, Time.deltaTime * rotateSpeed);}/// <summary>/// 計(jì)算周邊對(duì)象/// </summary>/// <param name="currentTF">當(dāng)前對(duì)象變換組件</param>/// <param name="distance">距離</param>/// <param name="angle">角度</param>/// <param name="targetTags">檢索目標(biāo)的標(biāo)簽</param>/// <returns></returns>public static Transform[] CalculateAroundTransform(Transform currentTF,float distance,float angle,string[] targetTags){//1.找到所有敵人List<Transform> list = new List<Transform>();foreach (var tag in targetTags){GameObject[] tempGos = GameObject.FindGameObjectsWithTag(tag);list.AddRange(ArrayHelper.Select(tempGos, o => o.transform));}//2.查找滿足條件的所有敵人:攻擊范圍內(nèi)list = list.FindAll(tf =>Vector3.Distance(tf.position, currentTF.position) <= distance &&Vector3.Angle(currentTF.forward, tf.position - currentTF.position) <= angle / 2);return list.ToArray();}
}
?
總結(jié)
- 上一篇: 【常用】单例
- 下一篇: 【常用】加载配置文件管理资源路径