【问题标题】:Gameobject not staying in same position relative to parent游戏对象相对于父对象不在同一位置
【发布时间】:2020-01-03 20:23:27
【问题描述】:

让我先说我知道这是一个常见问题,但是我已经寻找解决方案并没有提出任何问题。

此代码适用于由榴弹发射器实例化的榴弹。期望的行为是手榴弹在地面上弹跳,但粘在玩家身上。 3 秒后手榴弹爆炸。

我正在使用transform.parent 让手榴弹粘在玩家身上。

using UnityEngine;

// Grenade shell, spawned in WeaponMaster script.
public class GrenadeLauncherGrenade : MonoBehaviour
{
    #region Variables

    public float speed;
    public Rigidbody2D rb;
    public GameObject explosion;

    private int damage = 50;
    private GameObject col;


    #endregion

    // When the grenade is created, fly forward + start timer
    void Start()
    {
        rb.velocity = transform.right * speed;
        Invoke("Explode", 3f);
    }

    // Explode
    private void Explode()
    {
        Instantiate(explosion, gameObject.transform.position, Quaternion.identity);

        try
        {
            if (col.tag == "Player")
            {
                Debug.Log("Hit a player");
                col.GetComponent<PlayerHealth>().TakeDamage(damage);
            }
        }

        catch (MissingReferenceException e)
        {
            Debug.Log("Could no longer find a player, they are probally dead: " + e);
        }

        Destroy(gameObject);
    }

    // Check if the shell hits something
    private void OnCollisionEnter2D(Collision2D collision)
    {
        col = collision.gameObject;

        if (col.tag == "Player")
        {
            gameObject.transform.parent = col.transform;
            Debug.Log("Stick!");
        }
    }
}

更奇怪的是,在检查器中,手榴弹看起来像是父母,但它的行为却表明并非如此。我可以移动 TestPlayer,但手榴弹没有跟随。

【问题讨论】:

  • 弹丸的检查器设置是什么?您可以将其添加为屏幕截图吗?
  • @HoloLady 确定,现在就这样做

标签: c# unity3d parent collision


【解决方案1】:

非运动学刚体使它们附加的变换独立于任何祖先变换移动。这是为了避免物理引擎和祖先变换的运动变化之间的冲突。

因此,为了使手榴弹的变换保持相对于父变换,您应该使手榴弹的Rigidbody2D 在与玩家碰撞时运动。此外,将其 angularVelocityvelocity 归零:

// Check if the shell hits something
private void OnCollisionEnter2D(Collision2D collision)
{
    col = collision.gameObject;

    if (col.tag == "Player")
    {
        rb.isKinematic = true;
        rb.velocity = Vector2.zero;
        rb.angularVelocity = 0f;
        gameObject.transform.parent = col.transform;

        Debug.Log("Stick!");
    }
}

【讨论】:

  • 这适用于添加rb.velocity = new Vector2(0, 0);,非常感谢!我会接受你的回答,因为我刚刚用手榴弹组件的屏幕截图更新了帖子,有人可能会在那里发现一个简单的错误。
  • @Wzrd 好点。我还添加了一条线来将其角速度归零。谢谢指正!
  • 太棒了 - 感谢您的帮助,祝您有美好的一天:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 2020-07-02
相关资源
最近更新 更多