Guest User

Curve Weighted Random Unity

a guest
Apr 6th, 2022
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 KB | None | 0 0
  1. using System.Linq;
  2. using UnityEngine;
  3. using Random = UnityEngine.Random;
  4.  
  5. public class CurveRandom : MonoBehaviour
  6. {
  7.     private const float Step = 0.001f;
  8.     [SerializeField] private AnimationCurve _curve;
  9.     private void Start()
  10.     {
  11.         var weights = CalcWeights(5);
  12.         for (int i = 0; i < 100000; i++)
  13.         {
  14.             Debug.Log(WeightedRandom(weights));
  15.         }
  16.     }
  17.    
  18.     private float[] CalcWeights(int itemsCount)
  19.     {
  20.         float[] result = new float[itemsCount];
  21.         float curvePos = 0;
  22.         float partSize = 1f / itemsCount;
  23.         for (int i = 0; i < itemsCount; i++)
  24.         {
  25.             while (curvePos < (i + 1) * partSize)
  26.             {
  27.                 result[i] += _curve.Evaluate(curvePos);
  28.                 curvePos += Step;
  29.             }
  30.         }
  31.  
  32.         return result;
  33.     }
  34.     public static int WeightedRandom(float[] weights)
  35.     {
  36.         float value = Random.Range(0,  weights.Sum());
  37.         float weightSum = 0;
  38.         for (int i = 0; i < weights.Length; i++)
  39.         {
  40.             weightSum += weights[i];
  41.             if (value < weightSum)
  42.             {
  43.                 return i;
  44.             }
  45.         }
  46.         return weights.Length - 1;
  47.     }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment