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

  • 相关阅读:
    文字有阴影效果
    asp.net(c#)将彩色图片变灰阶图片
    C#异步调用的方法
    PHP获取指定月份的第一天开始和最后一天结束的时间戳函数
    php 获取当前用户的IP
    网站前端性能优化
    grep命令的使用
    学C++的经验总结
    主键、唯一键与唯一索引的区别
    shell的比较运算符
  • 原文地址:https://www.cnblogs.com/vitah/p/3842941.html
Copyright © 2011-2022 走看看