您的位置:首页 > 其它

按概率输出相应的随机数

2016-01-01 19:25 411 查看
#pragma strict

var probArray :float[];

private var probValue:int;

probArray = {0.5,0.25,0.05,0.02};

function OnGUI(){

if (GUI.Button(Rect(10,70,50,30),"Click"))

{

probValue = Choose(probArray);

switch(probValue){

case 0:

Debug.Log("NPC向我敬礼了");

break;

case 1:

Debug.Log("NPC离开了");

break;

case 2:

Debug.Log("NPC打我了");

break;

case 3:

Debug.Log("NPC给我钱了");

break;

default:

Debug.Log("我没碰到NPC");

}

}

}

function Choose(probs: float[]):int {

var total = 0.0;

for (elem in probs) {

// Debug.Log(elem);

total += elem;

// Debug.Log(total);

}

var randomPoint = Random.value * total;

var i:int;

for (i = 0; i < probs.Length;i++) {

if (randomPoint < probs[i])

return i;

else

randomPoint -= probs[i];

}

return probs.Length - 1;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: