Skip to content

Instantly share code, notes, and snippets.

@miguelSantirso
Created February 4, 2016 18:58
Show Gist options
  • Save miguelSantirso/e2183e42cb37b80d9e7f to your computer and use it in GitHub Desktop.
Save miguelSantirso/e2183e42cb37b80d9e7f to your computer and use it in GitHub Desktop.
[Unity] Easy image cinematic
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ImageCinematic : MonoBehaviour
{
[System.Serializable]
private struct CinematicStep
{
public float seconds;
public Sprite sprite;
}
#region inspector properties
[SerializeField]
private bool autoDestroy = true;
[SerializeField]
private Image imageA;
[SerializeField]
private Image imageB;
[SerializeField]
private CinematicStep[] cinematicSteps;
[SerializeField]
private float fadeOutSeconds = 0.7f;
#endregion
private bool finished = false;
private int nextCinematicStep = 0;
private float secondsForNextStep = -1;
public bool Finished { get { return finished; } }
public void Next()
{
var numSteps = cinematicSteps.Length;
if (nextCinematicStep < numSteps)
{
var step = cinematicSteps[nextCinematicStep];
nextCinematicStep += 1;
imageB.sprite = imageA.sprite;
imageB.color = imageA.color;
imageA.sprite = step.sprite;
imageA.color = new Color(1f, 1f, 1f, 0f);
secondsForNextStep = step.seconds;
}
else
{
finished = true;
if (autoDestroy)
StartCoroutine(AnimateDestroy());
}
}
public void ForceFinish()
{
finished = true;
StartCoroutine(AnimateDestroy());
}
void Start()
{
Next();
}
void Update()
{
if (secondsForNextStep >= 0)
{
secondsForNextStep -= Time.deltaTime;
if (secondsForNextStep < 0)
Next();
}
var maxDelta = (1f / fadeOutSeconds) * Time.deltaTime;
ImageMoveAlphaTowards(imageA, 1f, maxDelta);
ImageMoveAlphaTowards(imageB, 0f, maxDelta);
imageB.enabled = !Mathf.Approximately(imageB.color.a, 0f);
}
IEnumerator AnimateDestroy()
{
secondsForNextStep = -1;
enabled = false;
var t = 0f;
var secondsElapsed = 0f;
var transparent = new Color(1f, 1f, 1f, 0f);
while (t < 1)
{
t = secondsElapsed / fadeOutSeconds;
secondsElapsed += Time.deltaTime;
var colorA = Color.Lerp(imageA.color, transparent, t);
var colorB = Color.Lerp(imageB.color, transparent, t);
imageA.color = colorA;
imageB.color = colorB;
yield return null;
}
Destroy(gameObject);
}
private void ImageMoveAlphaTowards(Image image, float target, float maxDelta)
{
var imageAlpha = Mathf.MoveTowards(image.color.a, target, maxDelta);
var imageColor = image.color;
imageColor.a = imageAlpha;
image.color = imageColor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment