c# - 如何在 Unity 中编写精灵之间的渐变过渡?
问题描述
我有 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);
}
}
}
}
它们在生成的那一刻似乎都是可见的,它们不会消失,甚至根本不会被破坏。问题是什么?
谢谢。
解决方案
正如评论所暗示的,使用动画是一种可行的选择。但是,您的代码将无法正常工作,因为 alpha 接受从 0 到 1 而不是 0 到 255 的值。所以只需调整逻辑以从 1 淡入到 0,您应该会看到淡入淡出过渡。
推荐阅读
- python - 为什么 Python linecache 会影响 traceback 模块,但不会影响常规 traceback?
- oozie - 是否可以在不指定 inputDir 和 outputDir 的情况下运行 Oozie Spark Action
- linux - 当我在命令行中时,如何判断 Docker 映像正在运行什么 Linux?
- r - 删除文档中的文本并将其替换为空格
- asp.net - ASP.NET - 如何使用实体框架进行内部连接
- c# - 某些文件上 Xamarin.Android 上的 UnauthorizedAccessException
- xml - 从 XML 文件的两个不同标签中获取值并使用 XSLT 连接提取的值
- c# - 在执行其他操作时观看文件
- c++ - 如果 Else 语句缩进重要与否?(C++)
- javascript - React 中 HTML 标记的自动完成功能在 VS Code 中不起作用