How can I change the speed of my particles during runtime?
I'm currently programming a 2D Endless Runner, that gets faster as the ingame time moves on. Whenever the Player jumps or lands some particles spawn. As the particles did not look good actually moving forward just like the Player while every other object moved backwards, I wanted to give them a negative velocity, but I don't know how to change the particles speed through a script during runtime (to be honest I don't even know how to properly do it via the editor) and make the particles change their speed during lifetime after they are already emitted. So I'm thankful to any useful answer on this problem I encountered.
Answer by Hellium · Aug 08, 2019 at 12:53 PM
For upcoming particles :
Following code not tested
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
ParticleSystem particleSystem;
void Start()
{
particleSystem = GetComponent<ParticleSystem>();
}
public void SpeedUpParticles( float acceleration )
{
var velocityOverLifetime = particleSystem.velocityOverLifetime;
velocityOverLifetime.xMultiplier += acceleration;
velocityOverLifetime.yMultiplier += acceleration;
velocityOverLifetime.zMultiplier += acceleration;
}
}
For already emitted particles:
https://docs.unity3d.com/ScriptReference/ParticleSystem.GetParticles.html
https://docs.unity3d.com/ScriptReference/ParticleSystem.Particle-velocity.html
Following code not tested
using UnityEngine;
[RequireComponent(typeof(ParticleSystem))]
public class ExampleClass : MonoBehaviour
{
ParticleSystem particleSystem;
ParticleSystem.Particle[] particles;
void Start()
{
particleSystem = GetComponent<ParticleSystem>();
}
public void SpeedUpParticles( float acceleration )
{
particles = new ParticleSystem.Particle[particleSystem.main.maxParticles];
int aliveParticlesCount = particleSystem.GetParticles(particles);
// Change only the particles that are alive
for (int i = 0; i < aliveParticlesCount; i++)
{
particles[i].velocity = particles[i].velocity.normalized * (particles[i].velocity.magnitude + delta);
}
particleSystem.SetParticles(particles, aliveParticlesCount);
}
}
Your answer