我的对象在Unity中取消捕捉对象的错误

时间:2019-03-04 18:03:20

标签: c# unity3d scripting

我在测试场景中具有基本的对象捕捉功能,但是当我取消捕捉对象时,捕捉的对象将重新捕捉,除非我将其快速移开。 对于场景设置的上下文,我想在VR中实现捕捉对象,因此我要移动的对象内部有一个较小的父对象,以表示该对象在VR中作为父对象的手。另外,我在“手”对象上附加了捕捉脚本(下面的第一个脚本),并在手及其附加的方形obj上使用触发碰撞器。

有什么线索可以解决这个问题,这样我就不需要快速拉动来解耦物体了吗?

Video of the bug happening

下面是我用来实现此目的的脚本

    public class snap : MonoBehaviour, collider_helper.collider_help_reciever
{
    public Transform snapObj;
    public Transform SnapTarget;
    bool snapped = false;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public void OnTriggerEnter (Collider other)
    {
        Debug.Log("enter");
        if (snapped == false && other.transform.GetInstanceID() == SnapTarget.GetInstanceID())
        {
            snapObj.position = SnapTarget.position;
            snapObj.rotation = SnapTarget.rotation;
            snapObj.parent = SnapTarget;
            snapped = true;
        }
    }
    public void OnTriggerExit(Collider other)
    {

        Debug.Log("exit");
        if (snapped == true && other.transform.GetInstanceID() == SnapTarget.GetInstanceID())
        {
            snapObj.position = transform.position;
            snapObj.rotation = transform.rotation;
            snapObj.parent = transform;
            snapped = false;
            StartCoroutine(noSnap);
        }
    }
}

    public class collider_helper : MonoBehaviour {
    public GameObject recieving;
    collider_help_reciever reciever;
    // Use this for initialization
    void Start () {
        reciever = recieving.GetComponent<collider_help_reciever>();
    }

    // Update is called once per frame
    void Update () {

    }

    void OnTriggerStay (Collider other)
    {
        reciever.OnTriggerEnter(other);
    }
    public interface collider_help_reciever
    {
        void OnTriggerEnter(Collider other);
    }

}

1 个答案:

答案 0 :(得分:0)

好吧,答案是添加一个浮点数(lastSnapTime)来存储对象上一次解耦的时间,并且仅当它们上一次解耦后经过了一段时间才允许进行捕捉:

    public void OnTriggerEnter(Collider other)
{
    Debug.Log("enter");
    if (other.transform.GetInstanceID() == SnapTarget.GetInstanceID())
    {
        if (lastSnapTime + 0.1f < Time.time)
        {
            snapObj.position = SnapTarget.position;
            snapObj.rotation = SnapTarget.rotation;
            snapObj.parent = SnapTarget;
        }
    }
}
public void OnTriggerExit(Collider other)
{

    Debug.Log("exit");
    if (other.transform.GetInstanceID() == SnapTarget.GetInstanceID())
    {
        lastSnapTime = Time.time;
        snapObj.position = transform.position;
        snapObj.rotation = transform.rotation;
        snapObj.parent = transform;
        //StartCoroutine(noSnap);
    }
}