我正在 Unity 中工作一个重力模拟。 我让两个物体碰撞时合并,根据质量和大小进行合并。 我希望他们发生完全无弹性的碰撞(即他们合并,动量被保存)但尽管我的代码是正确的(我认为),它仍然有问题。

以下是检测碰撞的代码:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision != null && collision.gameObject.CompareTag("body"))
    {
        Rigidbody2D rbSelf = GetComponent<Rigidbody2D>();
        Rigidbody2D rbOther = collision.gameObject.GetComponent<Rigidbody2D>();

        if (rbSelf != null && rbOther != null && rbSelf.mass >= rbOther.mass)
        {
            rbSelf.linearVelocity = ((rbOther.mass * rbOther.linearVelocity) + (rbSelf.mass * rbSelf.linearVelocity)) / (rbSelf.mass + rbOther.mass);//完全无弹性碰撞计算
            rbSelf.mass += rbOther.mass;
            float size = Mathf.Pow((Mathf.Pow(collision.gameObject.transform.localScale.x, 3f) + Mathf.Pow(transform.localScale.x, 3f)), 1f/3f);
            transform.localScale = new Vector3(size, size, size);
            Destroy(collision.gameObject);
        }
    }
}

以下是视频链接:视频