【U3D】粒子沿特定路徑移動

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/wdmzjzlym/article/details/51353840


本系列文章由CSDN@萌萌的一天 出品,未經博主允許不得轉載。


      U3D中粒子是三維空間中渲染出來的二維圖像,通常來說,一個粒子系統是由粒子發射器、動畫器和渲染器組成的。我們可以通過腳本來控制粒子系統上的每個粒子,接下來主要講解一下如何讓粒子發射器中產生的粒子沿特定路徑進行移動。

      首先呢創建一個粒子發射器,我們打算讓其中產生的粒子按照如下(P1--->P2--->P3--->P4--->P5)的方向依次移動,就是下圖這樣的思路:

       

     

      假設一下,如果我們通過一個數組來記錄每個粒子的位置,讓它們依次遵循直線進行移動,這樣粒子會排列成一條直線,會產生這樣的運動效果:     


這種效果不是我想要的,我希望粒子移動能夠像這樣,它們的方向不變,但是不會排列成一條線,比如這樣:


     

      

      考慮一下,爲了實現這個目的, 需要創建一個位置的數組(比如P1到P5的postion),一個表示方向的數組,之後每幀判斷粒子的位置,根據當前粒子的位置來決定它的移動方向,當粒子到達任意一點,如果它還在生命週期內,就讓它移動到下一個點。

      OK,思路大致如此,打開U3D開始實現效果~~~

      首先,我們需要在Hierarchy面板上點擊右鍵創建一個Particle System(粒子系統),這樣系統會自動生成一個發射器,並且默認調用Particle Shader來渲染產生的粒子。

       由於新創建的粒子系統會的Shape自動調用Cone類型,我們需要把它改爲Box,這樣粒子就會沿着一條直線進行運動:


然後在新創建的Particle System上新創建一個腳本TestParticleMovement,代碼如下所示:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TestParticleMovement : MonoBehaviour
{
    public List<Vector3> nodes;   
    public Vector3[] directions;
    private ParticleSystem particles;
	void Start ()
	{
	    GetComponent<ParticleSystem>().startLifetime = nodes.Count;
	    if (nodes.Count == 0)
	        Debug.LogError("請添加至少1個node");
        //自動生成方向
        directions = new Vector3[nodes.Count];
        for (int i = 0; i < nodes.Count; i++)
            directions[i] = (nodes[i] - ((i - 1 >= 0) ? nodes[i - 1] : transform.position));
	}
	void Update ()
	{
        particles = GetComponent<ParticleSystem>();
        ParticleSystem.Particle[] particleList = new ParticleSystem.Particle[particles.particleCount];
	    int partCount = particles.GetParticles(particleList);
	    for (int i = 0; i < partCount; i++)
	    {
            // 計算粒子當前的生命
	        float timeALive = particleList[i].startLifetime - particleList[i].lifetime;
	        float dist = GetAddedMagnitude((int) timeALive);
	        int count = 0;
            //判斷位置信息
	        while (dist > GetAddedMagnitude(count))
	        {
	            count++;
	            particleList[i].velocity = directions[count];
	        }
	    }
        particles.SetParticles(particleList, partCount);
	}
    private float GetAddedMagnitude(int count)
    {
        float addedMagnitude = 0;
        for (int i = 0; i < count; i++)
        {
            addedMagnitude += directions[i].magnitude;
        }
        return addedMagnitude;
    }
}

這樣就能讓粒子正確的沿着設置的點進行移動了。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章