Exemplo n.º 1
0
    private void Update()
    {
        // Mouse left button released
        if (Input.GetMouseButtonUp(0))
        {
            Ray ray = _raycastCamera.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                _lineRenderer.startColor = Color.white;
                _lineRenderer.endColor   = _lineRenderer.startColor;
                if (_polygonOutline.Count > 1)
                {
                    _lineRenderer.startColor = Color.green;
                    _lineRenderer.endColor   = _lineRenderer.startColor;
                }

                _gateEdgeOverlap = false;
                if (_lineRenderer.positionCount > 2)
                {
                    if (EdgeOverlapsOutline(_lineRenderer.GetPosition(_lineRenderer.positionCount - 1), hit.point))
                    {
                        return;
                    }

                    if (EdgeOverlapsOutline(hit.point, _lineRenderer.GetPosition(0)))
                    {
                        _lineRenderer.startColor = Color.red;
                        _lineRenderer.endColor   = _lineRenderer.startColor;
                        _gateEdgeOverlap         = true;
                    }
                }

                GameObject go = Instantiate(_pointPrefab);
                go.transform.position = hit.point + _positionOffset;

                _polygonOutline.Add(go);

                _lineRenderer.positionCount = _polygonOutline.Count;
                _lineRenderer.SetPositions(_polygonOutline.Select(gam => gam.transform.position).ToArray());
            }
            else
            {
                Debug.LogError("Mouse position raycast failed, this should never happen!");
            }
        }
        else if (Input.GetKeyUp(KeyCode.Return) && !_gateEdgeOverlap)
        {
            if (_polygonOutline.Count < 3)
            {
                Debug.LogWarning("Cannot triangulate only one edge.");
                return;
            }

            Mesh      m    = new Mesh();
            Vector3[] edge = _polygonOutline.Select(gam => gam.transform.position).ToArray();
            m.vertices = edge;
            Triangulation.CapMesh(m, Enumerable.Range(0, edge.Length).ToList(), 0, _convexSupport);

            MeshObject outputGO = Instantiate(_outputGameObjectPrefab.gameObject).GetComponent <MeshObject>();
            outputGO.SetMesh(m);
            outputGO.SetPolygonCollider(edge.Select(v3 => new Vector2(v3.x, v3.y)).ToArray());

            _polygonOutline.ForEach(go => Destroy(go));
            _polygonOutline.Clear();
            _lineRenderer.positionCount = _polygonOutline.Count;
            _lineRenderer.startColor    = Color.white;
            _lineRenderer.endColor      = _lineRenderer.startColor;
        }
    }