Imagine I have 2 gameobjects, red plate and apple. When game start(this is crucial), apple already on red plate(2 gameobjects already in contact). so if I move red plate, the apple is "parented" to red plate and follow the transform.

How can I do that in Unity3D? I look at the code Trigger and Collision, both of them need to at least a stage that 1 moving gameobject to collide the other, which I don't have that.

Any idea how to deal with this?

有帮助吗?

解决方案

I found the solution: Bounds.Intersect

As in:

var bounds1 = gameObject1.renderer.bounds;

var bounds2 = gameObject2.renderer.bounds;



if (bounds1.Intersects(bounds2))

{

    // do something

}

So with this, my problem solved.

其他提示

Probably the simplest implementation is to use OnTriggerEnter and OnTriggerExit to toggle the parenting of one object's transform to another, so that all children of the parent will accept the transform operations performed on the parent.

Example:

using UnityEngine;

[RequireComponent(typeof(BoxCollider))]
[RequireComponent(typeof(Rigidbody))]

public class
    PlateCollider : MonoBehaviour
{
    private void
        Awake()
    {
        rigidbody.isKinematic = false;
        rigidbody.useGravity = false;
        collider.isTrigger = false;
    }
}

And

using UnityEngine;

[RequireComponent(typeof(SphereCollider))]
[RequireComponent(typeof(Rigidbody))]

public class 
    AppleCollider : MonoBehaviour 
{
    private void
        Awake()
    {
        rigidbody.isKinematic = false;
        rigidbody.useGravity = false;
        collider.isTrigger = false;
    }

    private void
        OnCollisionEnter(Collision collision)
    {
        PlateCollider tryGetPlate = collision.gameObject.GetComponent<PlateCollider>();

        if (tryGetPlate != null)
        {
            transform.parent = tryGetPlate.gameObject.transform;
        }
    }

    private void
        OnCollisionExit(Collision collision)
    {
        PlateCollider tryGetPlate = collision.gameObject.GetComponent<PlateCollider>();

        if (tryGetPlate != null)
        {
            transform.parent = null;
        }
    }
}

There's many other ways you can use to compare the two objects. In this example I try to get the component on a colliding gameobject and check if the component reference exists. Collision tags might be a better option for you, it might not.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top