Как запрограммировать в Unity постепенный переход между спрайтами? - PullRequest
2 голосов
/ 04 апреля 2020

У меня есть анимация в 4 PNG-изображениях. Я хочу, чтобы кадры воспроизводились в течение 1/2 секунды в порядке 1-2-3-4-2-1 с переходами прозрачности.

То, что я написал, должно было иметь первый кадр появляются сразу же, когда генерируется родительский объект, содержащий различные спрайты, затем он становится прозрачным в течение 1/12 секунды, пока второй кадр становится непрозрачным, и так далее, пока последний кадр не завершит свой цикл прозрачно-непрозрачно-прозрачный.

Вероятно, это не самый эффективный способ, но я сделал префаб из пустого объекта, под которым размещены 6 спрайт-фреймов, каждому спрайту присваивается отдельный скрипт.

Я публикую первые три сценария в качестве примера:

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

public class Frame1 : MonoBehaviour
{
    private SpriteRenderer thisSprite;
    private Color alpha;
    private float timer;
    // Start is called before the first frame update
    void Start()
    {
        alpha.a = 255;
        thisSprite.GetComponent<SpriteRenderer>().color = alpha;
    }

    // Update is called once per frame
    void Update()
    {
        timer = timer + Time.deltaTime;
        alpha.a -= timer * 3060;
        thisSprite.GetComponent<SpriteRenderer>().color = alpha;
        if (timer >= 1/12)
        {
            Destroy(gameObject);
        }

    }
}

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

public class Frame2 : MonoBehaviour
{
    private SpriteRenderer thisSprite;
    private Color alpha;
    private float timer;
    private int direction;
    // Start is called before the first frame update
    void Start()
    {
        alpha.a = 0;
        thisSprite.GetComponent<SpriteRenderer>().color = alpha;
    }

    // Update is called once per frame
    void Update()
    {
        if (direction == 0)
        {
            timer = timer + Time.deltaTime;
            alpha.a += timer * 3060;
            thisSprite.GetComponent<SpriteRenderer>().color = alpha;
            if (timer >= 1/12)
            {
                direction = 1;
            }
        }
        if (direction == 1)
        {
            timer = timer - Time.deltaTime;
            alpha.a += timer * 3060;
            thisSprite.GetComponent<SpriteRenderer>().color = alpha;
            if (timer >= 1/6)
            {
                Destroy(gameObject);
            }
        }

    }
}

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

public class Frame3 : MonoBehaviour
{
    private SpriteRenderer thisSprite;
    private Color alpha;
    private float timer;
    private int direction;
    // Start is called before the first frame update
    void Start()
    {
        alpha.a = 0;
        thisSprite.GetComponent<SpriteRenderer>().color = alpha;
        timer -= 1 / 12;
    }

    // Update is called once per frame
    void Update()
    {
        if (direction == 0)
        {
            timer = timer + Time.deltaTime;
            alpha.a += timer * 3060;
            thisSprite.GetComponent<SpriteRenderer>().color = alpha;
            if (timer >= 1 / 12)
            {
                direction = 1;
            }
        }
        if (direction == 1)
        {
            timer = timer - Time.deltaTime;
            alpha.a += timer * 3060;
            thisSprite.GetComponent<SpriteRenderer>().color = alpha;
            if (timer >= 1 / 6)
            {
                Destroy(gameObject);
            }
        }

    }
}

Все они кажутся видимыми в момент их создания, и они не исчезают и даже не получают уничтожен на всех. В чем проблема?

Спасибо.

1 Ответ

0 голосов
/ 04 апреля 2020

Как показывают комментарии, использование анимации является жизнеспособной альтернативой. Тем не менее, ваш код не будет работать просто потому, что alpha принимает значение от 0 до 1 вместо 0 до 255. Так что просто настройте ваши logi c, чтобы они постепенно уменьшались с 1 до 0, и вы должны увидеть свои переходы исчезновения.

...