Skip to content

Instantly share code, notes, and snippets.

@chiuan
Forked from Protonz/TweenObservable.cs
Created March 18, 2017 08:44
Show Gist options
  • Save chiuan/4202ff92af2a8e23c81d2e7a2b92dd5f to your computer and use it in GitHub Desktop.
Save chiuan/4202ff92af2a8e23c81d2e7a2b92dd5f to your computer and use it in GitHub Desktop.
Using UniRx to create a TweenStream
using System;
using System.Collections;
using UniRx;
using UnityEngine;
namespace UniRx {
public static partial class CustomObservable {
/// <summary>
/// Tween in seconds
/// </summary>
public static IObservable<Vector2> Tween( Vector2 from, Vector2 to, float seconds ) {
Vector2 delta = to - from;
Func<float, Vector2> lerpFunc = ( progress ) => { return from + (delta * progress); };
return UniRx.Observable.FromMicroCoroutine<Vector2>(( observer, cancellationToken ) => TweenEveryCycleCore(observer, from, to, seconds, lerpFunc, cancellationToken), FrameCountType.Update);
}
public static IObservable<float> Tween( float from, float to, float seconds ) {
float delta = to - from;
Func<float, float> lerpFunc = ( progress ) => { return from + (delta * progress); };
return UniRx.Observable.FromMicroCoroutine<float>(( observer, cancellationToken ) => TweenEveryCycleCore(observer, from, to, seconds, lerpFunc, cancellationToken), FrameCountType.Update);
}
static IEnumerator TweenEveryCycleCore<T>( IObserver<T> observer, T from, T to, float seconds, Func<float,T> lerpFunc, CancellationToken cancellationToken ) {
if( cancellationToken.IsCancellationRequested ) yield break;
if( seconds <= 0 ) {
observer.OnNext(to);
observer.OnCompleted();
yield break;
}
float totalTime = 0f;
observer.OnNext(from);
while( true ) {
yield return null;
if( cancellationToken.IsCancellationRequested ) yield break;
totalTime += UnityEngine.Time.deltaTime;
if( totalTime >= seconds ) {
observer.OnNext(to);
observer.OnCompleted();
yield break;
}
else {
float normalizedTime = totalTime / seconds;
observer.OnNext(lerpFunc(normalizedTime));
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment