Mert Sevinc
Mert Sevinc

Reputation: 1027

How to detect which particle collided with a rigid body in Unity?

Lets say a rigid body is going through a bunch of particles that belong to a single particle system and you want each particle that collides with rigid body to bounce off. How would you do that ?

void OnParticleCollision(GameObject other) is called when a rigid body has collided with a Particle system. However, I need to know which particle in the particle system has collided with the body.

Any thoughts ?

Upvotes: 2

Views: 1475

Answers (1)

Lotan
Lotan

Reputation: 4283

With the ParticleSystem.GetParticles function you could catch all your "living" particles, then assign them an index (you should inherit from particle class as the Particle class do not have any index or id variable).

GertParticles:

https://docs.unity3d.com/ScriptReference/ParticleSystem.GetParticles.html

How do you access the individual particles of a particle system?: https://answers.unity.com/questions/639816/how-do-you-access-the-individual-particles-of-a-pa.html

As I said, particles do not have any ID to identify them, I know that do not seem the "optimal approach" but look this example from Unity documentation about SetCustomParticleData function (https://docs.unity3d.com/ScriptReference/ParticleSystem.SetCustomParticleData.html) they iterate all of them.

Also on the same page, you can see one example to assign unique ID to each particle when it is born:

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

public class ExampleClass : MonoBehaviour {

    private ParticleSystem ps;
    private List<Vector4> customData = new List<Vector4>();
    private int uniqueID;

    void Start() {

        ps = GetComponent<ParticleSystem>();
    }

    void Update() {

        ps.GetCustomParticleData(customData, ParticleSystemCustomData.Custom1);

        for (int i = 0; i < customData.Count; i++)
        {
            // set custom data to the next ID, if it is in the default 0 state
            if (customData[i].x == 0.0f)
            {
                customData[i] = new Vector4(++uniqueID, 0, 0, 0);
            }
        }

        ps.SetCustomParticleData(customData, ParticleSystemCustomData.Custom1);
    }
}

Upvotes: 3

Related Questions