0
\$\begingroup\$

I have a car that I move with a Physics-based movement (AddForce(), AddTorque(), etc...) and I have a simple particle system attached behind the car as follows:

I'd like to play this ParticleSystem whenever the car moves; I tried checking if the car's rigidbody's velocity was greater than 0:

if(m_Rigidbody.velocity.z > 0)
   m_ParticleSystem.Play();

if(m_Rigidbody.velocity.z == 0 && m_ParticleSystem.isPlaying) // velocity.z == 0 is unreliable, verified with Debug.Log
   m_ParticleSystem.Stop();

I then tried using Input:

if(Input.GetAxis("Vertical") > 0) // the car is moving along the positive z axis
    m_ParticleSystem.Play();
if(Input.GetAxis("Vertical") == 0 && m_ParticleSystem.isPlaying)
    m_ParticleSystem.Stop();

These two methods don't work, I'm probably making assumptions on how Rigidbody.velocity behaves (when you stop the car for example, it becomes negative, so the particle system would keep playing until it reaches 0);

\$\endgroup\$
5
  • \$\begingroup\$ General practice is to avoid comparing floats for exact equality. Very rarely will gameplay be precise to the 10^-45 level needed to compare exactly equal to zero. Does using a range threshold help, or is there still another issue here? \$\endgroup\$ – DMGregory Dec 29 '18 at 14:37
  • \$\begingroup\$ No matter what I try to do, the particle system doesn't start or stop.. Is this even the way I should be doing this? \$\endgroup\$ – user115399 Dec 29 '18 at 14:45
  • \$\begingroup\$ Where have you written this code? \$\endgroup\$ – DMGregory Dec 29 '18 at 14:46
  • \$\begingroup\$ I wrote this in Update(); It's not how this should be done though, since a statement like Input.GetAxis("Vertical") == 0 even if it was accurate, would result in multiple calls to m_ParticleSystem.Stop.. \$\endgroup\$ – user115399 Dec 29 '18 at 15:15
  • \$\begingroup\$ Are you familiar with the ParticleSystem’s ability to emit based on distance traveled? You may not need to do any coding at all. docs.unity3d.com/Manual/PartSysEmissionModule.html \$\endgroup\$ – Ed Marty Dec 30 '18 at 2:15
1
\$\begingroup\$

Using a range and selectively stopping emission seemed to work fine in my tests:

if (Input.GetAxis("Vertical") > 0.1f) {
    if (!particles.isEmitting)
        particles.Play();
} else if(particles.isEmitting) {
    particles.Stop(true, ParticleSystemStopBehavior.StopEmitting);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy