c# - 游戏对象相对于父对象不在同一位置

标签 c# unity3d parent collision

首先让我说我知道这是一个常见问题,但是我已经搜索了解决方案但一无所获。

此代码用于由榴弹发射器实例化的榴弹。理想的行为是手榴弹在地面上弹跳,但粘在玩家身上。 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,但手榴弹没有跟随。

Parented Image

Behaviour Image

Grenade Components

最佳答案

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

因此,为了使手榴弹的变换保持相对于父变换,您应该使手榴弹的 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!");
    }
}

关于c# - 游戏对象相对于父对象不在同一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729137/

相关文章:

c# - 将 C# 中的调试器附加到另一个进程

C# 等效于 c++ 中的 bool 运算符和 rhs

jquery - 向子元素添加另一个 CSS 样式,该子元素也是父元素

javascript - Bootstrap Accordion - 添加和删除父级

c# - 在 Xamarin Forms 编辑器中设置 CursorPosition

c# - Console.Out.Write() 在哪里获取 Windows 服务?

unity3d - 如何检测句子检测是否在语音到文本(Unity IBM Watson sdk)中完成?

opencv - 如何计算新的相机在3d空间中的位置和旋转,以在移动3d对象后获得完全相同的 View ?

c# - 如何在不知道速度的情况下计算轨迹的角度

javascript - 使用 javascript 链接所有 li 或 img 标签