获取实例化预制件的速度

问题描述

我从我的预制“子弹”中实例化刚体“克隆”以在我的项目中拍摄它们。我想获得我射击的每颗子弹(每个实例)的速度。在下面我的代码示例中:

 public GameObject throwstart;
 public Rigidbody Clone;
 public float bulletVeLocity { get; set; } = 1;
 ...
 ...
 void Update()
     {
         if (Input.GetKeyDown(KeyCode.Space))
         {
             Rigidbody Clone2;
             Clone2 = Instantiate(Clone,throwstart.transform.position,throwstart.transform.rotation);
             Clone2.GetComponent<Rigidbody>().AddForce(Clone2.transform.forward * bulletVeLocity,ForceMode.Impulse);
             Debug.Log("VeLocity Clone Instanz: " + Clone2.mass);
             Debug.Log("VeLocity Clone Instanz: " + Clone2.veLocity);
         }
     }

通过上面的代码,我得到了预制件的速度/质量(但速度总是 (0,0),质量是正确的)。我做错了什么,如何获得每个实例化子弹的速度?

解决方法

物理仅在下一次 FixedUpdate 调用中更新。

所以此时速度很可能仍然是0。

我宁愿简单地设置而不是强制

Clone2.velocity = bulletVelocity;

这对于初始化子弹完全没问题,因为在这里我们明确想要立即改变速度。

顺便说一下,Clone2.GetComponent<Rigidbody>() 非常多余.. Clone2 已经 Rigidbody


如果你真的想做你目前正在尝试的事情,你可能不得不等到 FixedUpdate 并做例如

void Update()
 {
     if (Input.GetKeyDown(KeyCode.Space))
     {
         var Clone2 = Instantiate(Clone,throwstart.transform.position,throwstart.transform.rotation);
         Clone2.AddForce(Clone2.transform.forward * bulletVelocity,ForceMode.Impulse);
         
         StartCoroutine(ShowVelocity(Clone2));
     }
 }

private IEnumerator ShowVelocity(Rigidbody rigidbody)
{
    yield return new WaitForFixedUpdate();

    Debug.Log("Mass Clone Instanz: " + rigidbody.mass);
    Debug.Log("Velocity Clone Instanz: " + rigidbody.velocity);
}