其他分享
首页 > 其他分享> > 【unity2D】基于对象池的残影拖尾效果

【unity2D】基于对象池的残影拖尾效果

作者:互联网

目标

当美术素材较少时,我们可以基于对象池来实现残影拖尾效果,增强游戏的画面表现。

基本思路

步骤1. 创建一个2DSprite,编辑该对象的Image,使其为我们所需要的拖尾图片。

步骤2. 写一个方法,使该对象Image-Color中的alpha通道值在指定时间内逐渐变小,即图片逐渐变透明。

步骤3. 把该对象作为prefab,放入对象池。需要时,访问对象池。

相关代码

以下代码挂载在该对象的prefab上

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

public class Trail : MonoBehaviour
{
    private Transform tailTrans;
    private SpriteRenderer tailSprite;
    private SpriteRenderer thisSprite;
    private Color tailColor;
    private float showTimePoint;//时间点
    public float showTime = 0.3f;//时间段
    public float alphaMax = 0.5f;
    public float alphaMin = 0f;
    private float timer = 0f;

    private void OnEnable()
    {
        showTimePoint = Time.time;
        timer = 0f;

        //复刻player的动作,位置,转动,大小
        tailTrans = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
        tailSprite = GameObject.FindGameObjectWithTag("Player").GetComponent<SpriteRenderer>();
        thisSprite = GetComponent<SpriteRenderer>();

        thisSprite.sprite = tailSprite.sprite;
        transform.position = tailTrans.position;
        transform.rotation = tailTrans.rotation;
        transform.localScale = tailTrans.localScale;
    }

    private void FixedUpdate()
    {
        Timer(showTime);

        thisSprite.color = new Color(1 , 1 , 1 , Mathf.Lerp(alphaMax , alphaMin , timer));

        //时间到了,放回池子
        if(Time.time >= showTimePoint + showTime)
        {
            gameObject.transform.parent.gameObject.GetComponent<DictionaryTest>().BackToPool(this.gameObject);
        }
    }

    private void Timer(float showTime)
    {
        float _mult = 1 / showTime;

        if((timer += Time.deltaTime * _mult) <= 1f)
        {
            timer += Time.deltaTime * _mult;
        }
        else 
        {
            timer = 1f;
        }
    }
}

最终效果

image

补充

另外,只需调整预设图片,就能实现大部分简单的拖尾效果。

标签:基于,unity2D,showTime,float,tailTrans,private,残影,thisSprite,public
来源: https://www.cnblogs.com/OtusScops/p/14810155.html