提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
本文章为本人阅读有关游戏源码所总结,可能这个效果很多人都可以自己实现,但我觉得源码里的写的比较规范,记录一下学习学习,若有不足之处望指正。
一、颜色渐变的作用
颜色渐变主要作用体现在物体的出现、消失不那么突兀,使用渐变改变透明度让其由全透明逐渐变为不透明或者反之。
二、源码分析
1.IMAGE 颜色渐变
代码如下(示例):
/// <summary>
/// 第一个参数是需要变色的图片,第二个参数是一秒之内翻几倍实现完动画,第三个参数是需要变化过去的颜色目标,这个颜色会瞬间转换过去,透明度会慢慢转过去
/// </summary>
/// <param name="target"></param>
/// <param name="duration"></param>
/// <param name="color"></param>
/// <returns></returns>
public static IEnumerator FadeImage(Image target, float duration, Color color)
{
if (target == null)
yield break;
float alpha = target.color.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / duration)
{
if (target == null)
yield break;
Color newColor = new Color(color.r, color.g, color.b, Mathf.SmoothStep(alpha, color.a, t));
target.color = newColor;
yield return null;
}
target.color = color;
}
Unity的UGUI中image的颜色转变用上面这个协程函数可以实现,这个函数的第一个参数传递的是需要改变的image对象,第二个参数用作与变化的速度,这个数字越大变化将会越慢,注意的是1是原本速度的值也就是1s内变化完成,第三个函数所需要变化的颜色,注意的是,我们这个函数的颜色的值是会瞬间变化的,透明度是逐渐变化的,主要就是Color newColor = new Color(color.r, color.g, color.b, Mathf.SmoothStep(alpha, color.a, t));
这段代码起到的作用。使用方法如下:
StartCoroutine(MMFade.FadeText(this.GetComponent<Text>(), 5, new Color(0, 0, 0, 0.2f)));
2.Text文本实现颜色渐变
代码如下(示例):
public static IEnumerator FadeText(Text target, float duration, Color color)
{
if (target == null)
yield break;
float alpha = target.color.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / duration)
{
if (target == null)
yield break;
Color newColor = new Color(color.r, color.g, color.b, Mathf.SmoothStep(alpha, color.a, t));
target.color = newColor;
yield return null;
}
target.color = color;
}
使用方法和上面完全一致
3.2D精灵实现颜色渐变
代码如下(示例):
public static IEnumerator FadeSprite(SpriteRenderer target, float duration, Color color)
{
if (target == null)
yield break;
float alpha = target.material.color.a;
float t = 0f;
while (t < 1.0f)
{
if (target == null)
yield break;
Color newColor = new Color(color.r, color.g, color.b, Mathf.SmoothStep(alpha, color.a, t));
target.material.color = newColor;
t += Time.deltaTime / duration;
yield return null;
}
Color finalColor = new Color(color.r, color.g, color.b, Mathf.SmoothStep(alpha, color.a, t));
target.material.color = finalColor;
}
使用方法和上面完全一致
4.思考
我之前做项目使用的方法基本也是使用协程控制变化,源码中的方法和我的相比显得更加完备,细节方面处理的很好,比如判空特例,代码可扩展性也很高,自己可以在里面加一些需要的功能。
此外我一般处理变化效果的时候,使用的一般是Lerp函数线性插值效果,源码是smooth平滑曲线效果,我做了测试可以看下对比效果,感觉在颜色变化上差别也不是很大。不知道性能方面如何。。。