实例化预制件,然后向其添加力(弹射物)- Unity

Instantiating a prefab and then adding a force to it (Projectile) - Unity

我正在尝试向 Unity 中实例化射弹的 Rigidbody 组件添加力。我想使用这种方法,因为它是一种简单的投掷机制,我只希望弹丸以小的抛物线轨迹移动。射弹预制件已附加到 Unity 编辑器中的此脚本,它确实有一个刚体组件。

到目前为止,这是我的代码:

private void ProjectileShoot()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) && !gameOver)
        {
            Rigidbody projectileRb = projectilePrefab.GetComponent<Rigidbody>();
            Instantiate(projectilePrefab, transform.position, 
                projectilePrefab.transform.rotation);
            projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);
        }
    }

射弹预制件按预期在玩家位置生成,但它会立即掉到地上。不管我申请多少throwForce

ProjectileShoot()顺便在Update()

我是 C# 和 Unity 的业余爱好者,这是我的第一个项目,因此非常感谢您的帮助。谢谢。

private void ProjectileShoot()
{
    if (Input.GetKeyDown(KeyCode.LeftShift) && !gameOver)
    {
        GameObject projectileGO = (GameObject) Instantiate(projectilePrefab, transform.position, 
            projectilePrefab.transform.rotation);

        Rigidbody projectileRb = projectileGO.GetComponent<Rigidbody>();
        projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);
    }
}

您之前所做的是试图从预制件中获取刚体,但是这是不可能的。相反,在实例化时通过将其设置为变量来从实例中获取 Rigidbody。

Rigidbody projectileRb = projectilePrefab.GetComponent<Rigidbody>();

引用预制件的刚体。

Instantiate(projectilePrefab, transform.position, 
            projectilePrefab.transform.rotation);

使用预制件实例化了一个新实体。

projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);

力应用于参考刚体。


您正在创建一个新实体但未访问其刚体,而是使用了预制件的刚体。要解决此问题,在实例化新实体(即预制件的游戏对象)时,保留对它的引用并使用它的刚体来施加力。

GameObject projectile = (GameObject) Instantiate(projectilePrefab, transform.position, 
projectilePrefab.transform.rotation);

Rigidbody rb = projectile.GetComponent<Rigidbody>();
projectileRb.AddForce(throwForce * Vector3.forward, ForceMode.Impulse);