KITASENJU DESIGN BLOG

memo, html, javascript, unity

seed対応random

seedで数値が固定される乱数が欲しい。

sbfl.net

↑こちらを参考にさせていただき、 Math.random()の代替となるようvalue()関数を新設しました

export class SRandom {

    x:number=0;
    y:number=0;
    z:number=0;
    w:number=0;

    public static instance:SRandom;


    public static random():number{
        if(SRandom.instance==null){
            SRandom.instance = new SRandom();
        }
        let n = SRandom.instance.nextInt(0,10000);
        return n/10000;
    }

    constructor(seed = 88675123) {
      this.x = 123456789;
      this.y = 362436069;
      this.z = 521288629;
      this.w = seed;
    }
    
    // XorShift
    public next():number{
      let t;
   
      t = this.x ^ (this.x << 11);
      this.x = this.y; this.y = this.z; this.z = this.w;
      return this.w = (this.w ^ (this.w >>> 19)) ^ (t ^ (t >>> 8)); 
    }
    
    // min以上max以下の乱数を生成する
    public nextInt(min:number, max:number):number {
      const r = Math.abs(this.next());
      return min + (r % (max + 1 - min));
    }

}
"FOOTER"