Created
May 3, 2023 07:52
-
-
Save pypy-vrc/a492bf838e84cf532e222f4a7b756208 to your computer and use it in GitHub Desktop.
UnityEngine.Random on JavaScript
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
class UnityEngine_Random { | |
/** | |
* @type {number[]} | |
*/ | |
a = [1234, 3159640283, 3392860520, 3460949513]; | |
/** | |
* @param {number} seed | |
*/ | |
initState(seed) { | |
let n = BigInt(seed >>> 0) & 4294967295n; | |
this.a[0] = Number(n); | |
for (let i = 0; i < 3; ++i) { | |
n = (1812433253n * n + 1n) & 4294967295n; | |
this.a[i + 1] = Number(n); | |
} | |
} | |
/** | |
* @returns {number} | |
*/ | |
xorshift128() { | |
const t = this.a[0] ^ (this.a[0] << 11); | |
this.a[0] = this.a[1]; | |
this.a[1] = this.a[2]; | |
this.a[2] = this.a[3]; | |
this.a[3] = (this.a[3] ^ (this.a[3] >>> 19) ^ t ^ (t >>> 8)) >>> 0; | |
return this.a[3]; | |
} | |
/** | |
* @param {number} min | |
* @param {number} max | |
* @returns {number} | |
*/ | |
randomRange(min, max) { | |
const r = (this.xorshift128() & 0x7fffff) * 0.0000001192093; | |
return min * r + max * (1 - r); | |
} | |
/** | |
* @param {number} min | |
* @param {number} max | |
* @returns {number} | |
*/ | |
randomRangeInt(min, max) { | |
if (min < max) { | |
return min + (this.xorshift128() % (max - min)); | |
} | |
if (min > max) { | |
return max + (this.xorshift128() % (min - max)); | |
} | |
return min; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment