zoukankan      html  css  js  c++  java
  • Unity 随机数的使用

      脚本语言:C# 

      一个比较常用的例子是游戏中的主角碰到场景中的NPC时,NPC会随机做出反应,例如有50%几率来友好的致敬,25%几率走开,20%几率反身攻击和%%的几率赠送礼物。

    创建一个NPCTest脚本,用于模拟NPC动作:

    using UnityEngine;
    using System.Collections;
    
    public class NPCTest : MonoBehaviour {
    
        //NPC动作几率
        float[] probArray = {0.5f , 0.25f , 0.2f , 0.05f};  
        int probValue;    //NPC选择值
    
        // Use this for initialization
        void Start () {
        }
        
        // Update is called once per frame
        void Update () {
        }
    
        //选择函数,返回NPC的选项下标值
        int Choose(float[] probe)
        {
            float total = 0.0f;
            for (int i=0; i < probe.Length; i++) {
                total += probe[i];        
            }
    
            // Random.value方法返回一个0—1的随机数
            float randomPoint = Random.value * total;
    
            for (int i=0; i < probe.Length; i++) {
                if(randomPoint<probe[i])
                    return i;
                else
                    randomPoint -= probe[i];
            }
    
            return probe.Length - 1;
        }
    
        void OnGUI(){
            if( GUI.Button(new 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");
                    break;
                }
            }
        }
    }

    点击Game视图中的Click按钮,可以看到打印出来的数据:

    参考链接:

      更为详细的介绍:http://blog.csdn.net/luyuncsd123/article/details/16919547

  • 相关阅读:
    分割线
    PTA 乙级 1053 住房空置率 (20分) C/C++
    5.12 记录
    单词统计
    eclipse导入项目jdk版本不一样
    5.6日 项目回顾
    5.5 记录
    5.3 记录
    5.2 记录
    5.1 记录
  • 原文地址:https://www.cnblogs.com/vitah/p/3842941.html
Copyright © 2011-2022 走看看