【问题标题】:How to get the position of a gameobject every frame?如何每帧获取游戏对象的位置?
【发布时间】:2023-01-02 20:10:55
【问题描述】:

我基本上想让一个游戏对象在到达空间中的某个位置后转身。我有一个预制件,创建游戏对象并使其随机移动。但是,打印位置值给我相同的值 (0,4,0),这基本上是产卵者的位置。我想要物体在空间中移动时的位置。这是代码:

If (Input.GetMouseButtonDown(0))
{
  direction = new Vector3(Random.Range(-1.0f,1.0f), Random.Range(-1.0f,1.0f),     Random.Range(-1.0f,1.0f)); 
 GameObject sphere = Instantiate(spherePrefab, transform.position, Quaternion.identity);
 sphere.GetComponent<Rigidbody>().velocity = direction * speed; // this moves the object randomly
 position = sphere.transform.position;
 Debug.Log(position); // This prints the spawners location every frame but no the spheres.

我只在场景中创建了一个生成器对象,并用我的脚本实例化了球体。

任何帮助表示赞赏!

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您没有更新您在日志中打印的值。

    position 变量仅保存预制件实例化时的世界位置。

    这是一个基于您的代码的基本脚本,它给出了您期望的世界位置。

    下面,spherePrefab 是一个 3D 游戏对象球体,我只在其上添加了一个具有默认参数的 Rigidbody。

    用例如下:按下鼠标按钮,然后观察 Unity 控制台。

    using UnityEngine;
    
    public class Test : MonoBehaviour
    {
        [SerializeField] GameObject spherePrefab;
    
        const float SPEED = 2f;
    
        // Initialization
        Vector3 _sphere_position = Vector3.zero;
        bool _display_log = false;
        GameObject _sphere_ref = null;
    
        void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 direction = new(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));
    
                _sphere_ref = Instantiate(spherePrefab, transform.position, Quaternion.identity);
                _sphere_ref.GetComponent<Rigidbody>().velocity = direction * SPEED; // this moves the object randomly
                _sphere_position = _sphere_ref.transform.position;
    
                Debug.Log(_sphere_position); // This prints the spawners location every frame but no the spheres.
    
                _display_log = true;
            }
    
            // This case is expected to be entered after setting sphere_ref in order not to be null
            if (_display_log)
            {
                // Update the value
                _sphere_position = _sphere_ref.transform.position;
    
                // Print it
                Debug.Log(_sphere_position);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多