Last active
May 21, 2021 13:26
-
-
Save Fonserbc/d061905a48555e583edc to your computer and use it in GitHub Desktop.
A boolean, written for use in Unity3D, that evaluates to true pseudo-randomly. Given a *baseProbability* from 0 to 1, it follows a Pseudo-Random Distribution inspired by http://wiki.teamliquid.net/dota2/Pseudo_Random_Distribution Every time it evaluates false, it increases the probability to evaluate true.
This file contains hidden or 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; | |
/** | |
* Source at https://gist.github.com/Fonserbc/d061905a48555e583edc | |
* Made by @fonserbc | |
* Inspired by Valve's PRNG in use in Dota 2 | |
*/ | |
public class PseudoRandomBoolean { | |
float _baseProbability; | |
float _currentProbability; | |
int iteration; | |
public float baseProbability { | |
get { | |
return _baseProbability; | |
} | |
set { | |
_baseProbability = value; | |
Reset(); | |
} | |
} | |
public PseudoRandomBoolean () { } | |
public PseudoRandomBoolean (float probability) { | |
baseProbability = probability; | |
} | |
public static implicit operator bool (PseudoRandomBoolean b) { | |
if (UnityEngine.Random.Range(0f, 1f) < b._currentProbability) { | |
b.Reset (); | |
return true; | |
} | |
else { | |
b._currentProbability += (1f - b._currentProbability)*b._baseProbability; | |
b.iteration ++; | |
return false; | |
} | |
} | |
public float GetCurrentProbability() { | |
return _currentProbability; | |
} | |
public void Reset() { | |
_currentProbability = _baseProbability; | |
iteration = 0; | |
} | |
public int GetIterationCount() { | |
return iteration; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment