在运行时将游戏对象捕捉到 Unity 3D 中的另一个游戏对象

Snapping game object to another game object in Unity 3D during runtime

此刻,我将我的游戏对象拖过屏幕;但是,我很难弄清楚如何让我的游戏对象捕捉到我场景中预先存在的游戏对象。如何让我的游戏对象在实例化后的 运行 时间内与另一个对象对齐?

public class DragObject : MonoBehaviour

{ 
    private Vector3 mOffset;
    private float mZCoord;

    void OnMouseDown()

    {
        mZCoord = Camera.main.WorldToScreenPoint(
        gameObject.transform.position).z;
        mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
    }

    private Vector3 GetMouseAsWorldPoint()

    {
        Vector3 mousePoint = Input.mousePosition;
        mousePoint.z = mZCoord;
        return Camera.main.ScreenToWorldPoint(mousePoint);
    }

    void OnMouseDrag()

    {
        transform.position = GetMouseAsWorldPoint() + mOffset;
    }

}

LoadAssets class:

public class LoadAssets : MonoBehaviour
{

    bool isCreated = false;
    bool isCreatedDrillbit = false;

    public void LoadBOP()

    {
        if (!isCreated)

        {
            GameObject instance = Instantiate(Resources.Load("BOP", typeof(GameObject))) as GameObject;
            isCreated = true;
        }

    }

    public void LoadDrillBit()

    {
        if (!isCreatedDrillbit)

        {
            GameObject instance = Instantiate(Resources.Load("Drillbit", typeof(GameObject))) as GameObject;
            isCreatedDrillbit = true;
        }

    }

}

编写一个脚本来检查某个其他对象的位置,如果它足够近,则使其成为自身的子对象并将其本地位置和旋转设置为默认值。另外,禁用拖动脚本:

public class SnapToMe : MonoBehaviour
{

    public GameObject target = null;
    public float snapDistance = 1f; 

    void FixedUpdate() 
    {
        if (target==null) return;

        if ( Vector3.Distance(transform.position, target.transform.position) <= snapDistance) )  
        {
            target.transform.parent = transform;
            target.transform.localRotation = Quaternion.identity;
            target.transform.localPosition = Vector3.zero;

            target.GetComponent<DragObject>().enabled = false;
        }
    }
}

在您要进行捕捉的对象上,在应该发生捕捉的位置添加一个子对象,并将捕捉脚本附加到它:

Bottle
└── Bottle snap point
    └── SnapToMe

然后当你创建帽的时候,把它告诉捕捉点:

Gameobject newCap = Instantiate(...);
Gameobject bottleSnapPoint = GameObject.Find(
        "Bottle snap point"); // or some other way to get a reference to the snap point

SnapToMe snapper = bottleSnapPoint.GetComponent<SnapToMe>();
snapper.target = newCap;
snapper.snapDistance = 2f; //whatever is appropriate