两个对象之间的夹点

时间:2019-05-16 23:18:58

标签: unity3d

我需要在两个物体之间抓握enter image description here,实际上,小方块是具有刚体的球员,大方块是帮助小方块在其上跳跃并继续在其他大方块上跳跃以到达目的地的物体。我需要当玩家跳跃并着陆在旋转的立方体上时,因此默认情况下它们之间应该有摩擦力,玩家应该随大立方体旋转以使其位于大立方体上。

预期结果是,具有刚体的小立方体也应与大立方体一起旋转,这是因为大立方体正在旋转并且在大立方体上:

my scene

2 个答案:

答案 0 :(得分:1)

您可以将小方块游戏对象设置为大方块游戏对象的子代。这应该是技巧。

enter image description here

----在评论后进行编辑

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

=>当玩家(小方块)在大方块上时,您的子玩家会更多地进入大方块。

=>当玩家(小方块)从大方块移开时,您的子游戏玩家会移至大方块。

如果您使用刚体,则可以使用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 Tutorial中的OnCollisioEnter和OnCollisionExit中的更多信息

Unity Tutorial

中标签的更多信息

答案 1 :(得分:0)

您可以尝试限制小立方体的刚体上的位置和旋转。之后,您可以调用constrains.none,以便您可以再次允许跳跃,并在每次小立方体与大立方体碰撞时执行此操作。希望对您有所帮助:)