kingBook

导航

CocosCreator 多个对象权重计算

//权重对象列表
var weightObjects=[
	{weight:100},
	{weight:80},
	{weight:500}
];

//总权重
var sumWeight=0;
for(var i=0;i<weightObjects.length;i++){
	sumWeight+=weightObjects[i].weight;
}

//随机数 [0, sumWeight)
var n=(Math.random()*sumWeight)|0;
//在总权重构成的线段上的各个起始点
var m=0;
for(var i=0;i<weightObjects.length;i++){
	var weightObj=weightObjects[i];
	//如果在权重范围内
	if(n>=m && n<m+weightObj.weight){
		//console.log("选择了这个对象:"+i);
		break;
	}
	m+=weightObj.weight;
}

posted on 2020-08-11 12:14  kingBook  阅读(307)  评论(0编辑  收藏  举报