Unity拖尾组件现实Collider效果 TrailRenderer Collider

目录

1.实现思路
2.记录小球生成时间
3.设置小球
4.移动拖尾,动态计算
5.测试
1.实现思路 unity自带组件TrailRenderer不带Collider,如果想实现碰撞触发功能怎么实现呢
在拖尾移动时生成小球,用小球colliderr当做触发器,动态计算小球的存在时间,超时后销毁
Unity拖尾组件现实Collider效果 TrailRenderer Collider
文章图片

2.记录小球生成时间 Point.cs记录小球生成时间,OnTriggerEnter内做触发处理
挂载到小球预设体上面

using UnityEngine; public class Point : MonoBehaviour { public float createTime; void OnTriggerEnter(Collider coll) { Debug.Log("Do something"); if (coll.tag == "Fruit") { Debug.Log("Trail colliderEnter"); //coll.GetComponent().OnHirt(50); } } }

3.设置小球 勾选IsTrigger,变为触发器
取消勾选MeshRenderer,不显示小球;测试时可以显示,测试完成后取消勾选
Unity拖尾组件现实Collider效果 TrailRenderer Collider
文章图片

4.移动拖尾,动态计算 本文用到了对象池,不用自行修改为GameObject.Instantiate、Destory
using UnityEngine; using System.Collections.Generic; using UnityEditor; public class DrawTrailCollider : MonoBehaviour { //拖尾特效持续时长 public static float overTime = 0.2f; public List pointList = new List(); private int maxPoints = 500; public int minPixelMove = 5; // Must move at least this many pixels per sample for a new segment to be recorded public float distanceFromCamera = 5.0f; private Vector3 previousPosition; private int sqrMinPixelMove; private bool canDraw = false; void Start() { sqrMinPixelMove = minPixelMove * minPixelMove; }void Update() { if (Input.GetKeyDown(KeyCode.Space))//调试 { EditorApplication.isPaused = true; }if (Input.GetMouseButtonDown(0)) { previousPosition = Input.mousePosition; AddPoint(GetMousePos()); canDraw = true; } else if (Input.GetMouseButton(0) && (Input.mousePosition - previousPosition).sqrMagnitude > sqrMinPixelMove && canDraw) { previousPosition = Input.mousePosition; AddPoint(GetMousePos()); CheckOverTime(); if (pointList.Count >= maxPoints) { canDraw = false; } } else { if (pointList.Count > 0) { CheckOverTime(); } } }Vector3 GetMousePos() { var p = Input.mousePosition; p.z = distanceFromCamera; //Vector3 pos = XHSDK.XHSDKManager.Instance.mainCam.ScreenToWorldPoint(p); Vector3 pos = Camera.main.ScreenToWorldPoint(p); return pos; }/// /// 增加顶点 /// public void AddPoint(Vector3 pos) { GameObject go = ObjectPool._instance.GetObject("Point", pos, Quaternion.identity); Point point = go.GetComponent(); point.createTime = Time.realtimeSinceStartup; pointList.Add(point); }void CheckOverTime() { //移除超时的点 for (int i = 0; i < pointList.Count; i++) { if (Time.realtimeSinceStartup - pointList[i].createTime > overTime) { ObjectPool._instance.SetObjectToPool(pointList[i].gameObject); pointList.Remove(pointList[i]); i--; } } } }


5.测试 【Unity拖尾组件现实Collider效果 TrailRenderer Collider】测试基本可以达到想要的效果

    推荐阅读