首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试在Unity中创建随机Vector3

尝试在Unity中创建随机Vector3
EN

Stack Overflow用户
提问于 2020-12-11 00:36:38
回答 1查看 709关注 0票数 2

我试图创建一个随机范围,但是Unity给我这个错误: UnityException: Vector3不允许从MonoBehaviour构造函数(或实例字段初始化器)中调用,而是在唤醒或启动中调用它。从MonoBehavior调用,名为'particleMover‘。这是我的代码:

代码语言:javascript
运行
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-11 00:39:20

代码语言:javascript
运行
复制
Vector3 direction = Random.insideUnitSphere;

你使用了(1,360),看起来你把方向和旋转搞混了。

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

此外,您还需要使用Time.deltaTime

代码语言:javascript
运行
复制
direction = moveSpeed * direction * Time.deltaTime;

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

更新答案:

代码语言:javascript
运行
复制
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;
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65238605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档