【问题标题】:GameObject position changing in world space after removed from parent从父级移除后,游戏对象在世界空间中的位置发生变化
【发布时间】:2016-07-26 09:31:15
【问题描述】:

我正在使用 Unity 开发一款游戏,我正在让一个敌人丢下他的武器。武器的向量(在本地空间中)是 (0, 0, 1.71),我正在使用以下函数:

void SetGunDrop()
{
    gun.SetParent (null);
    gun.GetComponent<Animator> ().enabled = false;
    Rigidbody rb = gun.GetComponent<Rigidbody> ();
    rb.isKinematic = false;
}

但是,在与父级分离后,武器在世界位置中转换为 (0, 0, 1.71),从敌人的身体转换到地图的中心。

有没有办法避免这种情况,让枪从它的位置直接落到地上?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我建议将枪变换的父级设置为 null 或设置为世界空间的变换,然后将放下枪的游戏对象的 X/Y/Z 变换值添加到变换的 X/Y/Z。

    void SetGunDrop() {
       var parentT = gun.parent.transform;
       gun.SetParent (null);
       gun.position += new Vector(parentT.x, parentT.y, parentT.z); 
       gun.GetComponent<Animator> ().enabled = false;
       Rigidbody rb = gun.GetComponent<Rigidbody> ();
       rb.isKinematic = false;
    }
    

    如果您想了解有关 Transform.SetParent() 的更多信息,请查看 Unity 的文档 here。有关移动 Unity 变换的更多信息,请参阅post。祝你好运!

    编辑:已更新以反映 gun 变量是变换游戏对象 :)

    【讨论】:

    • 对不起!我忘了补充! gun 变量是一个变换,我也试试你的建议,谢谢!
    【解决方案2】:

    解决这个问题的一个简单方法是在放下枪之前存储枪的世界位置。

    void SetGunDrop()
    {
        Vector3 tempPosition = gun.position;
        gun.SetParent (null);
        gun.position = tempPosition;
    
        gun.GetComponent<Animator> ().enabled = false;
        Rigidbody rb = gun.GetComponent<Rigidbody> ();
        rb.isKinematic = false;
    }
    

    这应该对你有用,祝你好运!

    【讨论】:

    • 问题是那也行不通。即使在我使用 Translate() 和您建议的方式设置了它的位置之后,枪仍然保持在相同的位置。但是,我找到了一个更清洁和优化的替代方案,但无论如何感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多