unity游戏开发中的随机算法

随机相关内容 C#实现 Unity直接可用

洗牌代码

//Fisher-Yates shuffle

static void Shuffle(T[] array)

{

int n = array.Length;

for (int i = 0; i < n; i++)

{

int r = i + Random.Range(0, n - i);

T t = array[r];

array[r] = array[i];

array[i] = t;

}

}

带权重随机代码

static public int GetRandomWeightedIndex(float[] weights)

{

// Get the total sum of all the weights.

float weightSum = 0;

for (int i = 0; i < weights.Length; ++i)

{

weightSum += weights[i];

}

// Step through all the possibilities, one by one, checking to see if each one is selected.

int index = 0;

int lastIndex = weights.Length - 1;

while (index < lastIndex)

{

// Do a probability check with a likelihood of weights[index] / weightSum.

if (Random.Range(0, weightSum) < weights[index])

{

return index;

}

// Remove the last item from the sum of total untested weights and try again.

weightSum -= weights[index++];

}

// No other item was selected, so return very last index.

return index;

}

伪随机C系数生成代码

static public float CfromP(float p)

{

float Cupper = p;

float Clower = 0f;

float Cmid;

float p1;

float p2 = 1f;

while (true)

{

Cmid = (Cupper + Clower) / 2f;

p1 = PfromC(Cmid);

if (Mathf.Abs(p1 - p2) <= 0f) break;

if (p1 > p)

{

Cupper = Cmid;

}

else

{

Clower = Cmid;

}

p2 = p1;

}

return Cmid;

}

private float PfromC(float C)

{

float pProcOnN = 0f;

float pProcByN = 0f;

float sumNpProcOnN = 0f;

int maxFails = Mathf.CeilToInt(1f / C);

for (int N = 1; N <= maxFails; ++N)

{

pProcOnN = Mathf.Min(1f, N * C) * (1 - pProcByN);

pProcByN += pProcOnN;

sumNpProcOnN += N * pProcOnN;

}

return (1f / sumNpProcOnN);

}

关于如何使用这上述C系数

unity游戏开发中的随机算法_第1张图片

每次触发概率从一个值开始递增,第N次的触发概率P(N) = C * N,比如25%的几率,C值大概为8.5%,运算流程如下:

第一次触发眩晕概率为8.5%

第二次为17%,以此类推递增

如果触发眩晕成功,则概率重新从8.5%开始递增计算。

unity学习交流群可以点击加入一起学习交流

你可能感兴趣的:(unity游戏开发中的随机算法)