Skip to content

Instantly share code, notes, and snippets.

@AaronMeyers
Created March 29, 2016 21:34
Show Gist options
  • Save AaronMeyers/833349c60a7d04b4035bb278d44c9e5a to your computer and use it in GitHub Desktop.
Save AaronMeyers/833349c60a7d04b4035bb278d44c9e5a to your computer and use it in GitHub Desktop.
using UnityEngine;
public class WeightedRandomNumber {
AnimationCurve _curve;
float[] _cumulativeWeights;
float _totalWeight;
float _step;
float _curveTime;
public WeightedRandomNumber( AnimationCurve curve, int numSamples )
{
_curve = curve;
_cumulativeWeights = new float[numSamples];
_totalWeight = 0.0f;
_step = 1.0f / numSamples;
_curveTime = _curve[curve.length-1].time;
for ( int i=0; i<numSamples; i++ )
{
var weight = _curve.Evaluate( _curveTime * i * _step + _step * .5f );
_totalWeight += weight;
_cumulativeWeights[i] = _totalWeight;
}
}
public float Value()
{
var randWeight = Random.value * _totalWeight;
var index = 0;
while ( randWeight > _cumulativeWeights[index] )
index++;
return Random.Range( index * _step * _curveTime, (index + 1) * _step * _curveTime );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment