首页 > 解决方案 > 夹在两个物体之间

问题描述

我需要两个物体之间的抓地力,在此处输入图像描述实际上小立方体是一个具有刚体的玩家,而大立方体是一个可以帮助小立方体跳上它并继续跳到其他大立方体上以到达目的地的物体。我需要当玩家跳跃并降落在旋转的立方体上时,它们之间应该有摩擦,默认情况下玩家应该用大立方体旋转,因为它在大立方体上。

预期的结果是具有刚体的小立方体也应该随着大立方体旋转,因为大立方体正在旋转并且在大立方体上:

我的场景

标签: unity3d

解决方案


您可以将小立方体游戏对象设置为大立方体游戏对象的子对象。这应该是诀窍。

在此处输入图像描述

----评论后编辑

如果您需要更改子层级(因为小立方体可以移开),那么您需要一个脚本来在需要时添加和删除子级。

=> 当玩家(小立方体)在大立方体上时,你就是大立方体的孩子。

=> 当玩家(小方块)离开大方块时,你就可以将玩家移到大方块。

如果您使用刚体,则可以使用OnCollisionEnterOnCollisionExit

您可以将此单一行为附加到大立方体上。

public class BigCubeScript : MonoBehaviour
{
    private void OnCollisionEnter(Collision other)
    {
        //check if the colliding object is player (here I'm using a tag, but you may check it as you prefer)
        if (other.gameObject.tag == "Player")
            //change the parent of the player, setting it as this cube
            other.transform.SetParent(this.transform);
    }

    void OnCollisionExit(Collision other)
    {
        if (other.gameObject.tag == "Player")
            //remove the player from the cube
            other.transform.SetParent(null);
    }
}

您还可以对玩家的旋转施加力,直到他停留在立方体上。在这种情况下,很好地平衡旋转力非常重要(您可以在编辑器中尝试)。

public class BigCubeScript : MonoBehaviour
{
    //you may change this to add or remove the force
    Vector3 _rotationForce = new Vector3(0, 5, 0);

    private void OnCollisionStay(Collision other)
    {
        var rigidbody = other.gameObject.GetComponent<Rigidbody>();
        Quaternion deltaRotation = Quaternion.Euler(_rotationForce * Time.deltaTime);
        rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
    }
}

本Unity 教程中 OnCollisioEnter 和 OnCollisionExit 的更多信息

本Unity 教程中标签的更多信息


推荐阅读