【问题标题】:Trying to create a random Vector3 in Unity尝试在 Unity 中创建随机 Vector3
【发布时间】:2020-12-10 16:36:38
【问题描述】:

我正在尝试创建一个随机 Vector3,但 Unity 给了我这个错误:UnityException: Range is not allowed to be called from a MonoBehaviour 构造函数(或实例字段初始化程序),而是在 Awake 或 Start 中调用它。从 MonoBehavior 'particleMover' 调用。 这是我的代码:

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

public class particleMover : MonoBehaviour
{
    public float moveSpeed;
    public float temperature;
    public Rigidbody rb;
    public Transform tf;
    static private float[] directions;

    // Start is called before the first frame
    void Start()
    {
        System.Random rnd = new System.Random();
        float[] directions = { rnd.Next(1, 360), rnd.Next(1, 360), rnd.Next(1, 360) };
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 direction = new Vector3(directions[0], directions[1], directions[2]);
        direction = moveSpeed * direction;
        rb.MovePosition(rb.position + direction);
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:
    Vector3 direction = Random.insideUnitSphere;
    

    而您使用了 (1, 360),似乎您将方向与旋转混淆了。

    Vector3(x, y, z) - x, y, z 是位置值,而不是角度。

    另外,需要使用Time.deltaTime

    direction = moveSpeed * direction * Time.deltaTime;
    

    更多信息:https://docs.unity3d.com/ScriptReference/Time-deltaTime.html

    更新答案:

    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using UnityEngine;
    
    public class particleMover : MonoBehaviour
    {
        public float moveSpeed;
        public float temperature;
        public Rigidbody rb;
        public Transform tf;
        private Vector3 direction = Vector3.zero;
    
        void Start()
        {
            direction = Random.insideUnitSphere;
        }
    
        void Update()
        {
            rf.position += direction * moveSpeed * Time.deltaTime;
            // If this script is attached to tf object
            // transform.position += direction * moveSpeed * Time.deltaTime;
        }
    }
    

    【讨论】:

    • 如何在开始定义然后在更新中使用? (对不起,如果这无关)
    • Vector3 方向 = Vector3.zero;无效开始(){方向=随机.insideUnitSphere; } void Update() { rf.position += 方向 * moveSpeed * Time.deltaTime; }
    • direction = Random.insideUnitSphere 不一定会返回归一化的方向向量。它在一个单位球内,而不是在它的表面上。所以你宁愿做direction = Random.insideUnitSphere.normalized;
    • 同意你的看法。我刚刚更新了答案?
    • 答案的第一部分是完全错误,@SatoshiNaoki。我已经编辑出来了。随意编辑。
    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多