Unity 粒子沿自定义路径运动

张开发
2026/5/30 4:40:44 15 分钟阅读
Unity 粒子沿自定义路径运动
最自由沿自定义折线 / 曲线路径完整代码适合跑道、轨迹、任意形状路径你点几个点粒子就跟着走第一步创建路径点在场景新建空物体 → 改名 PathRoot在它下面建几个子物体作为路径点摆成你要的形状第二步脚本直接复制挂在粒子物体上using System.Collections.Generic;using UnityEngine;public class ParticleFollowPath:MonoBehaviour{[Header(路径点按顺序拖入)]public ListTransformpathPoints;[Header(移动速度)]publicfloatmoveSpeed2f;[Header(是否循环路径)]public bool loopPathtrue;private ParticleSystem _particle;private ListVector3_path;privatefloat_distanceTravelled;voidStart(){_particleGetComponentParticleSystem();// 把路径点转为路径列表_pathnew ListVector3();foreach(var p in pathPoints)_path.Add(p.position);}voidUpdate(){if(_pathnull||_path.Count2)return;// 让粒子系统沿路径移动_distanceTravelledTime.deltaTime*moveSpeed;transform.positionGetPathPosition(_distanceTravelled);}// 获取路径上的位置Vector3GetPathPosition(floatdistance){floattotalLength0;for(inti0;i_path.Count-1;i)totalLengthVector3.Distance(_path[i],_path[i1]);if(loopPath)distance%totalLength;floatcurrentDist0;for(inti0;i_path.Count-1;i){floatsegmentVector3.Distance(_path[i],_path[i1]);if(distancecurrentDistsegment){floatt(distance-currentDist)/segment;returnVector3.Lerp(_path[i],_path[i1],t);}currentDistsegment;}return_path[_path.Count-1];}}使用方法把路径点按顺序拖进列表调速度运行 → 粒子自动沿着你摆的点运动

更多文章