首页 > 其他分享 >将Particle转成UGUI

将Particle转成UGUI

时间:2024-11-30 11:59:49浏览次数:3  
标签:textureSheetAnimation Particle particleUV Vector2 new 转成 position quad UGUI

在unity官方论坛看到的一个解决方案,可以将Particle直接转换成CanvasRenderer元素显示。
新建一个UIParticleSystem.cs脚本,将以下代码复制进去:

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

[ExecuteInEditMode]
[RequireComponent(typeof(CanvasRenderer))]
[RequireComponent(typeof(ParticleSystem))]
public class UIParticleSystem : MaskableGraphic
{

    public Texture particleTexture;
    public Sprite particleSprite;

    private Transform _transform;
    private ParticleSystem _particleSystem;
    private ParticleSystem.Particle[] _particles;
    private UIVertex[] _quad = new UIVertex[4];
    private Vector4 _uv = Vector4.zero;
    private ParticleSystem.TextureSheetAnimationModule _textureSheetAnimation;
    private int _textureSheetAnimationFrames;
    private Vector2 _textureSheedAnimationFrameSize;

    public override Texture mainTexture
    {
        get
        {
            if (particleTexture)
            {
                return particleTexture;
            }

            if (particleSprite)
            {
                return particleSprite.texture;
            }

            return null;
        }
    }

    protected bool Initialize()
    {
        // initialize members
        if (_transform == null)
        {
            _transform = transform;
        }

        // prepare particle system
        ParticleSystemRenderer renderer = GetComponent<ParticleSystemRenderer>();
        bool setParticleSystemMaterial = false;

        if (_particleSystem == null)
        {
            _particleSystem = GetComponent<ParticleSystem>();

            if (_particleSystem == null)
            {
                return false;
            }

            // get current particle texture
            if (renderer == null)
            {
                renderer = _particleSystem.gameObject.AddComponent<ParticleSystemRenderer>();
            }
            Material currentMaterial = renderer.sharedMaterial;
            if (currentMaterial && currentMaterial.HasProperty("_MainTex"))
            {
                particleTexture = currentMaterial.mainTexture;
            }

            // automatically set scaling
            _particleSystem.scalingMode = ParticleSystemScalingMode.Local;

            _particles = null;
            setParticleSystemMaterial = true;
        }
        else
        {
            if (Application.isPlaying)
            {
                setParticleSystemMaterial = (renderer.material == null);
            }
#if UNITY_EDITOR
            else
            {
                setParticleSystemMaterial = (renderer.sharedMaterial == null);
            }
#endif
        }

        // automatically set material to UI/Particles/Hidden shader, and get previous texture
        if (setParticleSystemMaterial)
        {
            Material material = new Material(Shader.Find("UI/Particles/Hidden"));
            if (Application.isPlaying)
            {
                renderer.material = material;
            }
#if UNITY_EDITOR
            else
            {
                material.hideFlags = HideFlags.DontSave;
                renderer.sharedMaterial = material;
            }
#endif
        }

        // prepare particles array
        if (_particles == null)
        {
            _particles = new ParticleSystem.Particle[_particleSystem.maxParticles];
        }

        // prepare uvs
        if (particleTexture)
        {
            _uv = new Vector4(0, 0, 1, 1);
        }
        else if (particleSprite)
        {
            _uv = UnityEngine.Sprites.DataUtility.GetOuterUV(particleSprite);
        }

        // prepare texture sheet animation
        _textureSheetAnimation = _particleSystem.textureSheetAnimation;
        _textureSheetAnimationFrames = 0;
        _textureSheedAnimationFrameSize = Vector2.zero;
        if (_textureSheetAnimation.enabled)
        {
            _textureSheetAnimationFrames = _textureSheetAnimation.numTilesX * _textureSheetAnimation.numTilesY;
            _textureSheedAnimationFrameSize = new Vector2(1f / _textureSheetAnimation.numTilesX, 1f / _textureSheetAnimation.numTilesY);
        }

        return true;
    }

    protected override void Awake()
    {
        base.Awake();

        if (!Initialize())
        {
            enabled = false;
        }
    }

    protected override void OnPopulateMesh(VertexHelper vh)
    {
#if UNITY_EDITOR
        if (!Application.isPlaying)
        {
            if (!Initialize())
            {
                return;
            }
        }
#endif

        // prepare vertices
        vh.Clear();

        if (!gameObject.activeInHierarchy)
        {
            return;
        }

        // iterate through current particles
        int count = _particleSystem.GetParticles(_particles);

        for (int i = 0; i < count; ++i)
        {
            ParticleSystem.Particle particle = _particles[i];

            // get particle properties
            Vector2 position = (_particleSystem.simulationSpace == ParticleSystemSimulationSpace.Local ? particle.position : _transform.InverseTransformPoint(particle.position));
            float rotation = -particle.rotation * Mathf.Deg2Rad;
            float rotation90 = rotation + Mathf.PI / 2;
            Color32 color = particle.GetCurrentColor(_particleSystem);
            float size = particle.GetCurrentSize(_particleSystem) * 0.5f;

            // apply scale
            if (_particleSystem.scalingMode == ParticleSystemScalingMode.Shape)
            {
                position /= canvas.scaleFactor;
            }

            // apply texture sheet animation
            Vector4 particleUV = _uv;
            if (_textureSheetAnimation.enabled)
            {
                float frameProgress = 1 - (particle.lifetime / particle.startLifetime);
                //                float frameProgress = textureSheetAnimation.frameOverTime.curveMin.Evaluate(1 - (particle.lifetime / particle.startLifetime)); // TODO - once Unity allows MinMaxCurve reading
                frameProgress = Mathf.Repeat(frameProgress * _textureSheetAnimation.cycleCount, 1);
                int frame = 0;

                switch (_textureSheetAnimation.animation)
                {

                    case ParticleSystemAnimationType.WholeSheet:
                        frame = Mathf.FloorToInt(frameProgress * _textureSheetAnimationFrames);
                        break;

                    case ParticleSystemAnimationType.SingleRow:
                        frame = Mathf.FloorToInt(frameProgress * _textureSheetAnimation.numTilesX);

                        int row = _textureSheetAnimation.rowIndex;
                        //                    if (textureSheetAnimation.useRandomRow) { // FIXME - is this handled internally by rowIndex?
                        //                        row = Random.Range(0, textureSheetAnimation.numTilesY, using: particle.randomSeed);
                        //                    }
                        frame += row * _textureSheetAnimation.numTilesX;
                        break;

                }

                frame %= _textureSheetAnimationFrames;

                particleUV.x = (frame % _textureSheetAnimation.numTilesX) * _textureSheedAnimationFrameSize.x;
                particleUV.y = Mathf.FloorToInt(frame / _textureSheetAnimation.numTilesX) * _textureSheedAnimationFrameSize.y;
                particleUV.z = particleUV.x + _textureSheedAnimationFrameSize.x;
                particleUV.w = particleUV.y + _textureSheedAnimationFrameSize.y;
            }

            _quad[0] = UIVertex.simpleVert;
            _quad[0].color = color;
            _quad[0].uv0 = new Vector2(particleUV.x, particleUV.y);

            _quad[1] = UIVertex.simpleVert;
            _quad[1].color = color;
            _quad[1].uv0 = new Vector2(particleUV.x, particleUV.w);

            _quad[2] = UIVertex.simpleVert;
            _quad[2].color = color;
            _quad[2].uv0 = new Vector2(particleUV.z, particleUV.w);

            _quad[3] = UIVertex.simpleVert;
            _quad[3].color = color;
            _quad[3].uv0 = new Vector2(particleUV.z, particleUV.y);

            if (rotation == 0)
            {
                // no rotation
                Vector2 corner1 = new Vector2(position.x - size, position.y - size);
                Vector2 corner2 = new Vector2(position.x + size, position.y + size);

                _quad[0].position = new Vector2(corner1.x, corner1.y);
                _quad[1].position = new Vector2(corner1.x, corner2.y);
                _quad[2].position = new Vector2(corner2.x, corner2.y);
                _quad[3].position = new Vector2(corner2.x, corner1.y);
            }
            else
            {
                // apply rotation
                Vector2 right = new Vector2(Mathf.Cos(rotation), Mathf.Sin(rotation)) * size;
                Vector2 up = new Vector2(Mathf.Cos(rotation90), Mathf.Sin(rotation90)) * size;

                _quad[0].position = position - right - up;
                _quad[1].position = position - right + up;
                _quad[2].position = position + right + up;
                _quad[3].position = position + right - up;
            }

            vh.AddUIVertexQuad(_quad);
        }
    }

    void Update()
    {
        if (Application.isPlaying)
        {
            // unscaled animation within UI
            _particleSystem.Simulate(Time.unscaledDeltaTime, false, false);

            SetAllDirty();
        }
    }

#if UNITY_EDITOR
    void LateUpdate()
    {
        if (!Application.isPlaying)
        {
            SetAllDirty();
        }
    }
#endif

}

  脚本依赖ParticleSystem控件,只能挂载在Paricle物体上。新建一个ParticleSystem将脚本拖上去就能用了!

https://blog.csdn.net/dark00800/article/details/73729947

标签:textureSheetAnimation,Particle,particleUV,Vector2,new,转成,position,quad,UGUI
From: https://www.cnblogs.com/gangtie/p/18578242

相关文章

  • 半导体制造领域中的粒子缺陷(Particle Defect)
    随着半导体技术的进步,制造过程中的质量控制已成为提高半导体器件性能和可靠性的核心。粒子缺陷不仅会显著降低器件的电气性能,例如导致电路短路或开路等故障,而且对器件的长期可靠性产生严重影响,从而增加了器件性能退化和失效的可能性。 Part1-引 言半导体制造行业是现代电......
  • WnRAR将rar后缀格式文件转成zip后缀格式
    前言全局说明使用winRAR自带的转换功能,可以最大程度的保留原始信息,比如:打包时间、CRC32值等一、说明环境:Windows11家庭版23H222631.3737WinRAR6.00(32位)二、rar转zip2.12.2选择要转换的文件右边可以根据类型筛选2.3选择要转成的格式zip2.4选......
  • SQLSERVER——XML转数据表输出(E10的PickList转成数据表)
    --声明XML变量并加载XML数据DECLARE@XMLASXML;SET@XML=N'<PickListType><Name>UDF_COLLECTION_TJ</Name><DisplayName>收款条件</DisplayName><Items><PickListItem><Id>合同签订</Id>......
  • 写一个把数字转成中文的方法,例如:101转成一百零一
    functionnumberToChinese(num){if(num<0||num>999999999999){return"超出范围";}constunits=["","十","百","千","万","十万","百万","千万","......
  • 黑马头条Day4-19启动ApArticleApplication时报错some of the beans in the applicatio
    文章目录1.错误呈现2.错误原因3.解决方案(注入ApArticleService改成注入ApArticleMapper)视频教程:黑马程序员Java项目实战微服务项目《黑马头条》开发全套视频教程,基于SpringBoot+SpringCloud+Nacos等企业级微服务架构项目解决方案1.错误呈现APPLICATIONFAILED......
  • golang从http请求中读取xml格式的body,并转成json
    推荐学习文档golang应用级os框架,欢迎stargolang应用级os框架使用案例,欢迎star案例:基于golang开发的一款超有个性的旅游计划app经历golang实战大纲golang优秀开发常用开源库汇总想学习更多golang知识,这里有免费的golang学习笔记专栏文章目录以下是在Go语言中从HTT......
  • UGUI(现成组合控件)
    DropDownScrollView ScrollBarsize是滚动条的填充程度Slider如果设置为静态,那么传入的值始终为自己设置的那个值InputFieldcontenttype为standard时可以设置linetype, 只读不改,就是可以复制,但是你已经不能输入了代码控制 ......
  • 粒子群算法(Particle Swarm Optimization,PSO)详解
    算法背景粒子群算法,也称粒子群优化算法或鸟群觅食算法(ParticleSwarmOptimization),缩写为PSO。粒子群优化算法是一种进化计算技术(evolutionarycomputation),1995年由Eberhart博士和kennedy博士提出,源于对鸟群捕食的行为研究。该算法最初是受到飞鸟集群活动的规律性启......
  • java list<Map<String,Object>> 转成对应的对象
    将List<Map<String,Object>>转换为对应的对象可以通过反射或手动映射来实现。以下是一个示例,演示如何使用手动映射的方式将List<Map<String,Object>>转换为对象列表。示例代码假设我们有一个简单的对象类User:publicclassUser{privateStringname;privateint......
  • 通过LiveGBS实现安防监控摄像头GB28181转成WebRTC流实现web浏览器网页无插件低延迟直
    @目录1、WebRTC超低延时直播2、WebRTC延时对比3、LiveGBS的低延时的WebRTC流4、分屏页面如何选择默认播放流5、无法播放Webrtc6、搭建GB28181视频直播平台1、WebRTC超低延时直播需要低延时的视频流监控播放,之前可以用rtmp的低延时播放(1秒左右),随着浏览器对rtmp的禁用,无插件的低延......