Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Linq;
- using UnityEngine;
- using Random = UnityEngine.Random;
- public class CurveRandom : MonoBehaviour
- {
- private const float Step = 0.001f;
- [SerializeField] private AnimationCurve _curve;
- private void Start()
- {
- var weights = CalcWeights(5);
- for (int i = 0; i < 100000; i++)
- {
- Debug.Log(WeightedRandom(weights));
- }
- }
- private float[] CalcWeights(int itemsCount)
- {
- float[] result = new float[itemsCount];
- float curvePos = 0;
- float partSize = 1f / itemsCount;
- for (int i = 0; i < itemsCount; i++)
- {
- while (curvePos < (i + 1) * partSize)
- {
- result[i] += _curve.Evaluate(curvePos);
- curvePos += Step;
- }
- }
- return result;
- }
- public static int WeightedRandom(float[] weights)
- {
- float value = Random.Range(0, weights.Sum());
- float weightSum = 0;
- for (int i = 0; i < weights.Length; i++)
- {
- weightSum += weights[i];
- if (value < weightSum)
- {
- return i;
- }
- }
- return weights.Length - 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment