从父对象移除后,游戏对象在世界空间中的位置发生变化

本文关键字:对象 位置 空间 变化 世界 游戏 | 更新日期: 2023-09-27 17:58:37

我正在和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),从敌人身体转换到地图中心。

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

从父对象移除后,游戏对象在世界空间中的位置发生变化

我建议将枪变换的父对象设置为null或世界空间的变换,然后将放下枪的GameObject的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的文档。关于移动Unity Transforms的更多信息,这里有一篇关于它的帖子。祝你好运!

编辑:更新以反映枪变量是一个转换游戏对象:)

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

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;
}

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