Last active
July 23, 2016 16:48
-
-
Save markohlebar/e27372660f93d81e0908d42c32707215 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class BlendTreeRandomizer : MonoBehaviour { | |
public Animator animator; //animator on which to act upon | |
public string key; //what is the key in the blend tree | |
public int numStates = 2; //how many states are there | |
public float minTime = 1.0f; //minimum time spent in a state | |
public float maxTime = 5.0f; //maximum time spent in a state | |
public float transitionTime = 0.5f; //time to transition from one state to the other | |
private float elapsedTime = 0.0f; | |
private float stateStep = 1.0f; | |
private float nextRandomTime = 0.0f; | |
private int lastState = 0; | |
private int currentState = 0; | |
private float currentStateValue = 0.0f; | |
private float transitionValue; | |
void Start () { | |
Debug.Assert(transitionTime <= minTime); | |
Debug.Assert(numStates > 1); | |
stateStep = 1.0f / (numStates - 1); | |
} | |
void Update () { | |
elapsedTime += Time.deltaTime; | |
if (elapsedTime >= nextRandomTime) { | |
ResetTime(); | |
UpdateState(); | |
} | |
if (lastState != currentState) { | |
float lastStateValue = lastState * stateStep; | |
float t = (Mathf.Abs(currentStateValue - lastStateValue) * elapsedTime) / transitionTime; | |
transitionValue = Mathf.Lerp(lastStateValue, currentStateValue, t); | |
//Finish the transition when the desired value is almost there | |
if (Mathf.Abs(transitionValue - currentStateValue) < 0.01) { | |
lastState = currentState; | |
transitionValue = currentStateValue; | |
} | |
UpdateAnimator(transitionValue); | |
} | |
} | |
void ResetTime () { | |
elapsedTime = 0.0f; | |
nextRandomTime = Random.Range(minTime, maxTime); | |
} | |
void UpdateState () { | |
currentState = GetNextState(); | |
currentStateValue = currentState * stateStep; | |
} | |
void UpdateAnimator (float value) { | |
animator.SetFloat(key, value); | |
} | |
int GetNextState () { | |
return Random.Range(0, numStates); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment