【问题标题】:How to detect which particle collided with a rigid body in Unity?Unity中如何检测哪个粒子与刚体碰撞?
【发布时间】:2018-11-23 04:10:48
【问题描述】:

假设刚体正在穿过属于单个粒子系统的一堆粒子,并且您希望与刚体碰撞的每个粒子都反弹。你会怎么做呢?

当刚体与粒子系统发生碰撞时调用void OnParticleCollision(GameObject other)。但是,我需要知道粒子系统中的哪个粒子与身体发生了碰撞。

有什么想法吗?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    使用ParticleSystem.GetParticles 函数,您可以捕获所有“活”粒子,然后为它们分配一个索引(您应该从粒子类继承,因为粒子类没有任何索引或 id 变量)。

    GertParticles:

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

    如何访问粒子系统的各个粒子?: https://answers.unity.com/questions/639816/how-do-you-access-the-individual-particles-of-a-pa.html

    正如我所说,粒子没有任何 ID 来识别它们,我知道这似乎不是“最佳方法”,但请查看 Unity 文档中有关 SetCustomParticleData 函数 (https://docs.unity3d.com/ScriptReference/ParticleSystem.SetCustomParticleData.html) 的这个示例,它们会迭代所有这些函数。

    同样在同一页面上,您可以看到一个在每个粒子出生时为其分配唯一 ID 的示例:

    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);
        }
    }
    

    【讨论】:

    • 我只对崩溃的粒子感兴趣。为什么我会得到所有活的粒子并迭代?没有简单的方法吗?
    • 我已经更新了问题以回答您的评论,如果有最佳方法,我不知道该怎么做,但是来自 Unity 的人^^'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多