Управляемые системы частиц в движке Unity

Видео урок о программируемых или управляемых системах частиц в движке Unity.

Автор: Сергей Тарабан

:ad:

Программируемая система частиц - это фича движка Unity, которая позволяет вам создавать и управлять системой частиц напрямую скриптом. Это очень полезная фишка если вам нужно управлять большим количество одинаковых объектов с максимальной производительностью или нужно реализовать свою логику поведения системы частиц.

В этом видео уроке я сделаю веревку в виде динамически изменяемой кривой, а также новогоднюю елку, используя управляемые системы частиц в Unity. Язык - английский.

Все ресурсы которые я использовал в уроке вы можете найти в пакете ниже.

Скачать пакетный файл Unity: CustomParticleSystem.unitypackage

 

Скрипт для управления частицами

Этот скрипт реализует простую обертку, которая позволит вам управлять системой частиц в Unity.
// ParticlesController script
// Copyright (C) 2013 Sergey Taraban 
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using UnityEngine; using System.Collections; using System.Collections.Generic; using System;

[RequireComponent(typeof(ParticleSystem))] public class ParticlesController : MonoBehaviour { public Color color = Color.white; public Vector3 segmentDir = new Vector3(1.0f, 0, 0); public float StartAngle = 0.0f;

private Mesh m_Mesh;
private int[] m_Indices;
private Vector2[] m_UVs;

ParticleSystem.Particle[] particles;
ParticleSystem mPrSystem;
int mCurrCount = 0;

static int MaxValueToHide = 10000;

private int mVertexCount = 0;
void Awake ()
{
	mPrSystem = particleSystem;
	mPrSystem.Play();
}

void Start()
{
}

void LateUpdate() {
	UpdateSegments();
}	

public void UpdateSegments()
{
	if(particles == null) {
		return;
	}

	mPrSystem.SetParticles(particles, mPrSystem.particleCount);
}

public bool IsReadyToUse()
{
	return mPrSystem.particleCount > 0;
}

public void SetVertexCount(int aCount)
{	
	if(particles == null) {
		particles = new ParticleSystem.Particle[mPrSystem.particleCount];
		mPrSystem.GetParticles(particles);
	}

	if(mCurrCount > aCount) {
		for(int i = aCount; i < mPrSystem.particleCount; i++) {
			particles[i].position = new Vector3(0, MaxValueToHide, 0);
		}			
	}

	mCurrCount = aCount < mPrSystem.particleCount ? aCount : mPrSystem.particleCount;		 		 		if(aCount > mPrSystem.particleCount) {
		Debug.LogError("SetVertexCount(): vertex count > particles cache");
	}
}

public void SetPosition(int aIndex, Vector3 aPosition)
{
	if(aIndex < 0 || aIndex >= mCurrCount) {
		return;
	}	

	particles[aIndex].position = aPosition;
	if(aIndex > 0) {
		Vector3 dir = (particles[aIndex].position - particles[aIndex-1].position);
		particles[aIndex].rotation = AngleAroundAxis(segmentDir, dir) + StartAngle;
		if(aIndex == 1) {
			dir = -(particles[0].position - particles[1].position);
			particles[0].rotation = AngleAroundAxis(segmentDir, dir) + StartAngle;
		} 
	}
}

public void SetColor(int aIndex, Color aColor)
{
	if(aIndex < 0 || aIndex >= mCurrCount) {
		return;
	}	

	particles[aIndex].color = aColor;
}

public void SetScale(int aIndex, float scale)
{
	if(aIndex < 0 || aIndex >= mCurrCount) {
		return;
	}	

	particles[aIndex].size = scale;
}

static float AngleAroundAxis ( Vector3 dirA, Vector3 dirB ) {
	float res = Vector3.Angle(dirA, dirB);
	res *= Vector3.Dot(Vector3.up, Vector3.Cross(dirA, dirB)) < 0.0f ? -1.0f : 1.0f;
	return res;
}

}

 

 Скрипт для создания кривой из частиц с функцией синуса

3D and 2D curves 3D и 2D кривые
// RopeTape script
// Copyright (C) 2013 Sergey Taraban 
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using UnityEngine; using System.Collections;

[RequireComponent(typeof(ParticlesController))] public class RopeTape : MonoBehaviour {

ParticlesController mParticlesController = null;

float timer = 0;
float mPhase = 0;

public float Amplitude = 10.0f;
public float AmplitudeZ = 5.0f;
public float XIncrement = 1.0f;
public float dx = 1.0f;
public float PhaseIncrement = 0.1f;
public float Width = 1.0f;

// Use this for initialization
void Start () {
	mParticlesController = GetComponent<ParticlesController>();
}

// Update is called once per frame
void Update () {
	mPhase += PhaseIncrement*Time.deltaTime*Mathf.PI;
	if(mParticlesController.IsReadyToUse()) 
	{
		timer += Time.deltaTime;
		int particlesNum = mParticlesController.particleSystem.particleCount;
		mParticlesController.SetVertexCount(particlesNum);
		float t = 0;
		float fy = 0;
		float fz = 0;
		float dl = 0.01f;
		for(int i = 0; i < particlesNum; i++) 
		{
			fy = Amplitude * Mathf.Sin(t + mPhase);
			fz = AmplitudeZ * Mathf.Sin(t + mPhase);
			mParticlesController.SetPosition(i, transform.position + new Vector3(dx*i, fy, fz));
			t += XIncrement*0.001f*Mathf.PI;
			mParticlesController.SetScale(i, Width);
		}
	}
}

}

 

Скрипт новогодней ёлки

unity christmas tree Новогодняя ёлка из частиц

Этот скрипт я использовал чтобы сделать новогоднюю елку в виде частиц.

// ChristmasTree script
// Copyright (C) 2013 Sergey Taraban 
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using UnityEngine;
using System.Collections;

public class ChristmasTree : MonoBehaviour {

	ParticlesController mParticlesController = null;
	float mCurrPhaseOffset = 0.0f;

	public int MaxParticlesNum = 800;
	public bool showAllAprticles = false;
	public float Height = 0.1f;
	public float startRadius = 0.5f;
	public bool fixedLineStep = true;
	public float lineStep = 0.05f;
	public float angleStep = 0.5f;
	public float particleScaleMax = 4.0f;
	public float rotateSpeed = 1.0f;

	float timer = 0;
	float mOldCangeColorTime = -10.0f;

	// Use this for initialization
	void Start () {
		mParticlesController = GetComponent();
		//mParticlesController.SetVertexCount(50);
	}

	// Update is called once per frame
	void Update () {
		if(mParticlesController.IsReadyToUse()) 
		{
			timer += Time.deltaTime;
			int particlesNum = showAllAprticles ? MaxParticlesNum : (int)Mathf.Lerp(1, MaxParticlesNum, timer/8.0f);
			mParticlesController.SetVertexCount(particlesNum);
			mCurrPhaseOffset += rotateSpeed * Time.deltaTime;
			if(mCurrPhaseOffset >= 360.0f) 
			{
				mCurrPhaseOffset = 360 - mCurrPhaseOffset;
			}
			float dAlpha = 0;
			float dL = lineStep;
			float heightOffset = 0.01f;
			float offset = heightOffset;
			bool isChangeColor = ((int)timer - mOldCangeColorTime >= 1.0f);
			if(isChangeColor)
			{
				mOldCangeColorTime = timer;
			}
			for(int i = 0; i < particlesNum; i++) 
			{
				float R = offset * startRadius;
				float angle = dAlpha + mCurrPhaseOffset;
				if(angle >= 360.0f) {
					angle = 360.0f - angle;
				}

				float x = R * Mathf.Cos(angle);
				float z = R * Mathf.Sin(angle);
				mParticlesController.SetPosition(i, new Vector3(x, Height*i, z) + transform.position );

				float coeff = (float)i/(float)particlesNum;
				if(isChangeColor) {
					Vector3 color = new Vector3(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
					color = color.normalized;
					mParticlesController.SetColor(i, new Color(color.x, color.y, color.z, 1.0f));
				}

				mParticlesController.SetScale(i, Mathf.Lerp(1.0f, particleScaleMax, coeff));

				if(fixedLineStep) 
				{
					dAlpha += dL * 180.0f / (Mathf.PI * R);
				} 
				else
				{
					dAlpha += angleStep;
				}
				offset += heightOffset;
			}
		}
	}
}

Автор: Сергей Тарабан

Почитать по теме