gpt4 book ai didi

c# - 尝试在 Unity 中创建一个随机 Vector3

转载 作者:行者123 更新时间:2023-12-05 02:46:55 30 4
gpt4 key购买 nike

我正在尝试制作一个随机 Vector3,但 Unity 给我这个错误:UnityException:不允许从 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);
}
}

最佳答案

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

关于c# - 尝试在 Unity 中创建一个随机 Vector3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65238605/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com