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