Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class RandomDistribution
- {
- Vector2 _range;
- Random _random;
- float _widthModifier;
- float _heightModifier;
- /* So here is the theory behind this. WARNING: calculus
- *
- * So we want to have some decent distribution of values
- * so that stuff is more likely to spawn in the center than on the sides.
- *
- * For that and simplicities sake we choose f(x)=1/(x^2+1)
- * Now we need to bring this distribution into a form where we can actually get a RANDOM value from that range.
- *
- * So we need to integrate this function, since we need to know how much of the randomness has been "used up" already
- * With that we end up with F(x)=atan(x)
- *
- * So next we need to map the values from 0 to 1 that the RANDOM class gives us to that.
- * So we take the inverse function of tan which is fortunately tan, hence this solution is simple and fast enough to use.
- */
- public RandomDistribution (Vector2 range, float steepness, int randomSeed=0)
- {
- if (steepness <= 0 || steepness >= 1)
- throw new ArgumentException("Steepness must be inbetween 0 and 1");
- if (range.X > range.Y)
- throw new ArgumentException("range.X must not be greater than range.Y");
- _random = randomSeed != 0 ? new Random(randomSeed) : Chunk.RANDOM;
- _range = range;
- //This defines how steep the values change in the end
- _widthModifier = (float)Math.PI * steepness /2;
- //This is to make sure our values are in a sensible range
- _heightModifier = (float)Math.Tan(_widthModifier)*2;
- }
- public float GetNext()
- {
- //[0,1]->[-1,1]
- double randomBetweenMinusOneAndOne = _random.NextDouble() * 2 - 1;
- //[-1,1]->[-_widthModifier,widthModifier]->[-0.5f,0.5f]
- double distributedValue = Math.Tan( randomBetweenMinusOneAndOne* _widthModifier)/_heightModifier;
- //[-0.5f,0.5f]->[0,1]
- double normalizedValue = distributedValue+0.5f;
- return (float)(_range.X + normalizedValue * (_range.Y - _range.X));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement