鼠标拖动克隆无限克隆

时间:2017-05-08 17:03:09

标签: c# unity3d

所以我正在制作一个马里奥制造商“克隆”,我希望它在我控制和拖动时实例化对象。它几乎无限的瓷砖。如果新位置与对象的旧位置相同,我希望它只创建一个对象。一切都按照1个1块的网格进行捕捉

public GameObject tilePrefab;

      void OnMouseDrag(){
        Vector2 pos = Input.mousePosition;
        pos = Camera.main.ScreenToWorldPoint (pos);
        pos.x = Mathf.Round(pos.x);
        pos.y = Mathf.Round(pos.y);
        transform.position = pos;
        if (Input.GetKey (KeyCode.LeftControl)) {
            if (transform.position != GameObject.Find ("SomePrefabName").transform.position) {
                GameObject myGameObject = Instantiate (tilePrefab) as GameObject;
                myGameObject.name = "SomePrefabName";
            }
        }
    }

Before Drag

After Drag

1 个答案:

答案 0 :(得分:1)

尝试改为:

public GameObject tilePrefab;
      void OnMouseDrag(){
        Vector2 pos = Input.mousePosition;
        pos = Camera.main.ScreenToWorldPoint (pos);
        pos.x = Mathf.Round(pos.x);
        pos.y = Mathf.Round(pos.y);
        transform.position = pos;
        var hitColliders = Physics.OverlapSphere(transform.position, 1);
        if (Input.GetKey (KeyCode.LeftControl)) {
            if (hitColliders.Length == 0) {
                GameObject myGameObject = Instantiate (tilePrefab) as GameObject;
                myGameObject.name = "SomePrefabName";
            }
        }
    }

这里我们使用Physics.OverlapSphere来检测我们是否在所需位置有一个碰撞器,如果不是这种情况,我们继续使用代码