【搬運】【Unity開發小技巧】Unity隨機概率擴展(概率可調控)
做了以下兩張圖有助于理解,如果想調控概率的話直接修改概率數組即可,實戰案例:http://t.csdn.cn/P9QKJ
其實在做概率類相關的界面效果的時候,我們真實做法都是在刷新界面前已經把結果獲取到了,然后根據結果去處理界面上的邏輯,一定要帶著這個思想去理解以下內容
一.做加法
1 /**加*/ 2 //rate:幾率數組(%), total:幾率總和(100%) 3 // Debug.Log(rand(new int[] { 10, 5, 15, 20, 30, 5, 5,10 }, 100)); 4 public static int rand(int[] rate, int total) 5 { 6 int r = Random.Range(1, total+1); 7 int t = 0; 8 for (int i = 0; i < rate.Length; i++) 9 { 10 t += rate[i]; 11 if (r < t) 12 { 13 return i; 14 } 15 } 16 return 0; 17 }
二.做減法
1 /**減*/ 2 //rate:幾率數組(%), total:幾率總和(100%) 3 // Debug.Log(randRate(new int[] { 10, 5, 15, 20, 30, 5, 5,10 }, 100)); 4 public static int randRate(int[] rate, int total) 5 { 6 int rand = Random.Range(0, total+1); 7 for (int i = 0; i < rate.Length; i++) 8 { 9 rand -= rate[i]; 10 if (rand <= 0) 11 { 12 return i; 13 } 14 } 15 return 0; 16 }
運行100次的結果:

————————————————
版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
原文鏈接:https://blog.csdn.net/qq_37310110/article/details/86139130
【敬畏能量 敬畏自然】

浙公網安備 33010602011771號