Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top