在Unity中尝试创建一个随机的Vector3

4
我正在尝试创建一个随机的Vector3,但Unity给了我这个错误:UnityException:Range不允许从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);
    }
}
1个回答

4
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;
    }
}

我该如何在开始时定义它,然后在更新中使用它?(如果这与主题无关,请原谅) - Spartan2909
Vector3 direction = Vector3.zero;void Start() { direction = Random.insideUnitSphere; }void Update() { rf.position += direction * moveSpeed * Time.deltaTime; } 向量3方向=向量3.零;开始(){ 方向=随机.在单位球内; }更新(){ RF.位置+=方向moveSpeed时间. deltaTime; } - Satoshi Naoki
1
direction = Random.insideUnitSphere doesn't necessarily return a normalized direction vector. It is inside a unit sphere, not on its surface. So you should rather do direction = Random.insideUnitSphere.normalized; - derHugo
另外,注意规范化一个已经被规范化的单位向量是不正确的。 - Fattie
这并不完全错误。只有在使用Random.Range(-1, 1)时需要使用direction.normalized。 - Satoshi Naoki
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接