贝塔(Beta)函数

作者:追风剑情 发布于:2019-10-12 10:11 分类:Algorithms

贝塔(Beta)函数是统计学中的密度函数,用来描述概率分布。可利用密度函数来设计游戏地图中不同位置的刷怪机率。

工具:Unity2018

示例

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class BetaCurve : MonoBehaviour
{
    public float P = 2;
    public float Q = 2;
    public RawImage rawImage;
    public Text text;
    public string savePath;
    public bool refresh = true;
    public bool save = false;

    void Update()
    {
        if (!refresh)
            return;
        refresh = false;
        //利用Beta函数在Texture上画曲线
        Texture2D texture = new Texture2D(100, 100);
        for (float t=0; t<=1; t+=0.01f)
        {
            float v = BetaLerp(t);
            int x = (int)(t * texture.width);
            int y = (int)(v * texture.width);
            texture.SetPixel(x, y, Color.red);
        }
        texture.Apply();
        rawImage.texture = texture;

        if (text)
            text.text = string.Format("P={0}\nQ={1}", P, Q);

        if (save)
            SavePNG(string.Format("{0}/P{1}_Q{2}.png", savePath, P, Q), texture);
    }

    float BetaLerp(float x)
    {
        //贝塔(Beta)函数
        float y = Mathf.Pow(x, P - 1) * Mathf.Pow(1 - x, Q - 1);
        return y;
    }

    public static void SavePNG(string filePath, Texture2D texture)
    {
        try
        {
            byte[] pngData = texture.EncodeToPNG();
            File.WriteAllBytes(filePath, pngData);
        }
        catch (Exception ex)
        {
            Debug.Log(ex.StackTrace);
        }
    }
}


运行测试

111.png 222.png 333.png 444.png

555.png 666.png 777.png 888.png 

999.png 10000.png 20000.png 300000.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号