gpt4 book ai didi

c# - 如何在 Unity 中编写 Sprite 之间的淡入淡出过渡?

转载 作者:行者123 更新时间:2023-12-05 07:10:56 24 4
gpt4 key购买 nike

我有一个包含 4 个 PNG 图像的动画。我想让帧在 1/2 秒的过程中以 1-2-3-4-2-1 的顺序播放,并带有透明度过渡。

我写的应该是当生成包含不同 Sprite 的父对象时第一帧立即出现,然后让它在 1/12 秒内变为透明,而第二帧变为不透明,依此类推,直到最后一帧结束其透明-不透明-透明循环。

这可能不是最有效的方法,但我制作了一个空对象的预制件,下面放置了 6 个 Sprite 帧,每个 Sprite 都有一个单独的脚本。

我将发布前三个脚本作为示例:

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

}
}

它们似乎在生成的那一刻就可见,而且它们不会消失,甚至根本不会被摧毁。什么问题?

谢谢。

最佳答案

正如评论所暗示的那样,使用动画是一种可行的替代方法。但是,您的代码将无法正常工作,因为 alpha 接受 0 到 1 之间的值,而不是 0 到 255 之间的值。因此,只需调整您的逻辑以从 1 淡入淡出到 0,您应该会看到淡入淡出过渡。

关于c# - 如何在 Unity 中编写 Sprite 之间的淡入淡出过渡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61027713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com