【搬运】【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

来源链接:https://www.cnblogs.com/moegarn/p/18723424

© 版权声明
THE END
支持一下吧
点赞6 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容