简体   繁体   English

Unity 在游戏中附加对象

[英]Unity Attaching objects in game

Hello I am having a problem and I dont know how to solve it.你好我有一个问题,我不知道如何解决它。 I want to create a 3d puzzle where the player needs to move multiple 3D objects to put them together.我想创建一个 3d 拼图,玩家需要移动多个 3D 对象将它们放在一起。 I already know how to implemet the movement (LeanTouch) but I need a way to recognize when two objects touch each other in special places.我已经知道如何实现运动(LeanTouch),但我需要一种方法来识别两个物体何时在特殊位置相互接触。 Then I would use transform to combine them.然后我会使用转换来组合它们。 Does anyone have an Idea how to solve this?有谁知道如何解决这个问题?

You should probably use colliders for that, and then use the collision event您可能应该为此使用对撞机,然后使用碰撞事件

One way to solve this is to create child objects with the colliders in the specific places you want to detect collision at.解决此问题的一种方法是在要检测碰撞的特定位置创建带有碰撞器的子对象。 Then in OnCollisionEnter() you can practically combine them by creating a new parent of the two objects.然后在 OnCollisionEnter() 中,您实际上可以通过创建两个对象的新父对象来组合它们。 Here's an example of an approach I took:这是我采用的方法的示例:

I set up my colliders like this:我这样设置我的对撞机: 对撞机设置

Then on the individual colliders I added this code.然后在单个对撞机上我添加了这段代码。 Front is just the tag attached to the collider shown in the hierarchy. Front 只是附加到层次结构中显示的对撞机的标签。

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Front"))
        {
            var newParent = new GameObject();
            newParent.transform.SetParent(collision.transform.parent.parent); // Get the parent of the current gameobject the collider is attached to
            collision.transform.parent.SetParent(newParent.transform); // Doing .parent because this is the child collider
            transform.parent.SetParent(newParent.transform);
        }
    }

It's not perfect, but the result is that the objects were combined under the same parent.这并不完美,但结果是对象被合并在同一个父级下。 在此处输入图像描述

Alternatively, you could simply make one cube the child of the other by removing NewParent and replacing it with collision.transform.parent.或者,您可以通过删除 NewParent 并将其替换为 collision.transform.parent 来简单地使一个立方体成为另一个立方体的子级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM