Unity API详解——Random类

Random类是Unity中用于产生随机数的类,不可以实例化,只有静态属性和静态方法。本博客主要介绍了Random类的一些静态属性。

一、Random类静态属性

在Random类中,涉及的静态属性有insideUnitCircle属性、insideUnitSphere属性、onUnitSphere属性、rotationUniform属性、rotation属性和seed属性。由于属性insideUnitCircle、insideUnitSphere和onUnitSphere功能相近,属性rotationUniform和rotation的功能也相近,于是把它们放到一起介绍,接下来详细介绍这些属性。

insideUnitCircle属性:圆内随机点

1、基本语法

public static Vector2 insideUnitCircle { get; } 

2、功能说明

此属性用于返回一个半径为1的圆内的随机点坐标,返回值为Vector2类型

notes:insideUnitSphere属性和onUnitSphere属性功能相似。

  • insideUnitSphere属性:返回一个半径为1的球内的随机点坐标,返回值为Vector3类型
  • insideUnitSphere属性:返回一个半径为1的球表面的随机点坐标,返回值为Vector3类型

3、代码实现

通过实例演示属性insideunitCircle、insideUnitSphere和onUnitSphere的使用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class insideUnitCircle_test : MonoBehaviour
{
    public GameObject go;
    void Start()
    {
        //每隔0.4秒执行一次use_rotationUniform方法
        InvokeRepeating("use_rotationUniform", 1.0f, 0.4f);
    }

    void use_rotationUniform()
    {
        //在半径为5的圆内随机位置实例化一个GameObject对象
        //Vector2实例转为Vector3时,z轴分量默认为0
        Instantiate(go, Random.insideUnitCircle * 5.0f, Quaternion.identity);
        //在半径为5的球内随机位置实例化一个GameObject对象
        Instantiate(go, Vector3.forward * 15.0f + 5.0f * Random.insideUnitSphere, Quaternion.identity);
        //在半径为5的球表面随机位置实例化一个GameObject对象
        Instantiate(go, Vector3.forward * 30.0f + 5.0f * Random.insideUnitSphere, Quaternion.identity);
    }
}

在这段代码中,首先声明了一个公共的GameObject变量go,然后再方法use_rotationUniform中分别使用Random属性insideUnitCircle、insideUnitSphere和onUnitSphere的返回值作为实例化对象的参考位置,最后在Start方法中调用InvokeRepeating方法,每隔0.4秒执行一次use_rotationUniform方法。
在这里插入图片描述
在这里插入图片描述

二、rotationUniform属性

均匀分布特征

1、基本语法

public static Quaternion rotationUniform { get; } 

2、功能说明

此属性用于返回一个随机且符合均匀分布特征的rotation值。所谓均匀分布特征,简单来说就是指每个可能出现的随机数的概率是相等的。例如,设随机数产生函数f(x)=x%7,x的取值范围为[0,10],则当x从0增大到10时,出现f(x)=0的次数有两次,分别为当x=0和x=7时;而f(x)=5的机会只有一次,即x=5时,所以f(x)的序列不是均匀分布的随机分布。为了使得f(x)中每个值出现的概率相等,可以把x的取值范围扩展为[0,7n],其中n为正整数,这样f(x)产生每个值得概率就相等了。

静态方法 英文解释 中文说明
void LoadLevel(int index); void LoadLevel(string name); Loads the level by its name or index. 根据场景名称和索引号加载场景
void LoadLevelAdditive(int index);void LoadLevelAdditive(string name); Loads a level additively. 根据场景名称和索引号加载场景,但是当前场景的物体不销毁
** AsyncOperation LoadLevelAsync(int index); AsyncOperation LoadLevelAsync(string levelName); ** Loads the level asynchronously in the background. 异步加载场景
** AsyncOperation LoadLevelAdditiveAsync(int index); AsyncOperation LoadLevelAdditiveAsync(string levelName);** Loads the level additively and asynchronously in the background. 异步加载场景而且当前物体不销毁
** void Quit();** Quits the player application. 退出游戏
** void CancelQuit();** Cancels quitting the application. T his is useful for showing a splash screen at the end of a game. 取消应用退出。
** bool CanStreamedLevelBeLoaded(int levelIndex);** Can the streamed level be loaded? 获得当前levelindex的场景是否被加载。
** void CaptureScreenshot(string filename, int superSize = 0);** Captures a screenshot at path filename as a PNG file. 截屏。
** void OpenURL(string url);** Opens the url in a browser. 在浏览器中访问网址
** AsyncOperation RequestUserAuthorization(UserAuthorization mode);** Request authorization to use the webcam or microphone in the Web Player. 请求获得权限
** void ExternalCall(string functionName, params object[] args);** alls a function in the containing web page (Web Player only). 在webplayer 调用一个javaScrip函数。
** void ExternalEval(string script); ** Evaluates script snippet in the containing web page (Web Player only). 在webplayer上执行javascrip片段。
** float GetStreamProgressForLevel(int levelIndex);** How far has the download progressed? [0…1]. 下载进度。
** bool HasUserAuthorization(UserAuthorization mode);** pCheck if the user has authorized use of the webcam or microphone in the Web Player. 检测用户是否有webcam和手机在webpalyer的权限

1、规范化向量:

Vector3 normalized = position.normalized;

2、向量加法:

Vector3 vectorA = new Vector3(1.0f, 1.0f, 1.0f);
Vector3 vectorB = new Vector3(2.0f, 2.0f, 2.0f);
Vector3 sum = vectorA + vectorB;

3、向量减法:

Vector3 vectorA = new Vector3(1.0f, 1.0f, 1.0f);
Vector3 vectorB = new Vector3(2.0f, 2.0f, 2.0f);
Vector3 difference = vectorA - vectorB;

4、向量乘法:

Vector3 vectorA = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 scaled = vectorA * 2.0f;

5、向量除法:

Vector3 vectorA = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 scaled = vectorA / 2.0f;

6、计算两个向量的点积:

Vector3 vectorA = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 vectorB = new Vector3(4.0f, 5.0f, 6.0f);
float dot = Vector3.Dot(vectorA, vectorB);

7、计算两个向量的叉积

Vector3 vectorA = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 vectorB = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 cross = Vector3.Cross(vectorA, vectorB);

8、将向量缩放为指定大小:

Vector3 vectorA = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 scaled = Vector3.Scale(vectorA, new Vector3(2.0f, 2.0f, 2.0f));

9、对向量进行旋转变换:

三、实例

使用C#和Unity中的Vector3类开发的简单游戏示例。游戏的玩法非常简单,玩家需要控制一个小球,避开障碍物,尽可能多地吃到食物。

1、创建物体

首先,我们需要创建一个空物体并将其命名为“Ball”。将以下代码附加到该物体上,以使其能够移动:

using UnityEngine;

public class Ball : MonoBehaviour
{
    public float speed = 10f; // 移动速度

    private Rigidbody rb; // 刚体组件

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // 移动
    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.AddForce(movement * speed);
    }
}

这将使小球在水平和垂直方向上移动。接下来,我们需要创建一些障碍物和食物。为此,我们可以使用Unity的基本图形对象,如Cube和Sphere,并在它们上面添加随机的初始位置和不同的颜色。

2、计分系统

让我们为游戏添加一个计分系统。每当小球吃到一个食物时,分数将增加,并且游戏将生成一个新的食物。同样,每当小球撞到一个障碍物时,游戏将结束。

using UnityEngine;
using UnityEngine.UI;

public class GameController : MonoBehaviour
{
    public Text scoreText; // 文本组件
    public GameObject foodPrefab; // 食物对象
    public GameObject[] obstacles; // 障碍物对象数组
    public int foodCount; // 食物数量

    private int score = 0; // 分数

    // 初始化
    void Start()
    {
        // 创建障碍物
        for (int i = 0; i < obstacles.Length; i++)
        {
            Vector3 position = new Vector3(Random.Range(-10.0f, 10.0f), 0.5f, Random.Range(-10.0f, 10.0f));
            Instantiate(obstacles[i], position, obstacles[i].transform.rotation);
        }

        // 创建食物
        for (int i = 0; i < foodCount; i++)
        {
            Vector3 position = new Vector3(Random.Range(-10.0f, 10.0f), 0.5f, Random.Range(-10.0f, 10.0f));
            Instantiate(foodPrefab, position, foodPrefab.transform.rotation);
        }

        // 显示分数
        UpdateScoreText();
    }

    // 更新分数
    void UpdateScoreText()
    {
        scoreText.text = "SCORE: " + score;
    }

    // 加分
    public void AddScore(int value)
    {
        score += value;
        UpdateScoreText();
    }

    // 游戏结束
    public void GameOver()
    {
        // 显示游戏结束画面

        // 重载场景
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

在此代码中,我们使用了UnityEngine.UI命名空间中的Text组件来显示分数。每当小球吃到一个食物时,我们将在计分系统中加一分
在这里插入图片描述

四、总结

总之,Vector3是一个灵活且功能强大的类,非常适用于3D游戏场景中的各种数学计算。无论是计算两个向量之间的点积、叉积还是将向量缩放、旋转,都可以使用Vector3类轻松实现。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>