Skip to content

Instantly share code, notes, and snippets.

@Fonserbc
Last active May 21, 2021 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Fonserbc/d061905a48555e583edc to your computer and use it in GitHub Desktop.
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.
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