示例#1
0
    IEnumerator EnableCollider(float seconds, EdgeCollider2D platform)
    {
        yield return(new WaitForSeconds(seconds));

        platform.enabled = true;
    }
    void Start()
    {
        Mesh mesh = new Mesh();

        GetComponent <MeshFilter>().sharedMesh = mesh;

        BezierSpline spline = GetComponent <BezierSpline>();


        //Vector2[] uv =
        //;

        //int[]

        Vector2[] points = spline.GetPoints();

        EdgeCollider2D ec = gameObject.AddComponent <EdgeCollider2D>();

        Vector2[] edgePoints = new Vector2[points.Length / 3 * resolution + 1];

        for (int i = 0; i < points.Length - 1; i += 3)
        {
            for (int j = 0; j < resolution; j++)
            {
                edgePoints[i / 3 * resolution + j] = Bezier.GetPoint(points[i], points[i + 1], points[i + 2], points[i + 3], j / (float)resolution);
            }
        }

        edgePoints[edgePoints.Length - 1] = points[points.Length - 1];

        ec.points = edgePoints;


        Debug.Log(edgePoints.Length);


        Vector3[] verts     = new Vector3[edgePoints.Length * 3];
        Vector2[] uv        = new Vector2[edgePoints.Length * 3];
        int[]     triangles = new int[(edgePoints.Length - 1) * 12];


        for (int i = 0; i < edgePoints.Length; i++)
        {
            Vector2 point = edgePoints[i];
            verts[i * 3 + 0] = new Vector3(point.x, point.y, -1);
            verts[i * 3 + 1] = new Vector3(point.x, point.y, 1);
            verts[i * 3 + 2] = new Vector3(point.x, -100, 0);

            uv[i * 3 + 0] = new Vector2(0, 0);
            uv[i * 3 + 1] = new Vector2(0, 0);
            uv[i * 3 + 2] = new Vector2(0, 0);

            if (i > 0)
            {
                int j = i - 1;
                triangles[j * 12 + 0] = j * 3 + 0;
                triangles[j * 12 + 1] = j * 3 + 1;
                triangles[j * 12 + 2] = j * 3 + 3;

                triangles[j * 12 + 3] = j * 3 + 1;
                triangles[j * 12 + 4] = j * 3 + 4;
                triangles[j * 12 + 5] = j * 3 + 3;

                triangles[j * 12 + 6] = j * 3 + 2;
                triangles[j * 12 + 7] = j * 3 + 0;
                triangles[j * 12 + 8] = j * 3 + 5;

                triangles[j * 12 + 9]  = j * 3 + 0;
                triangles[j * 12 + 10] = j * 3 + 3;
                triangles[j * 12 + 11] = j * 3 + 5;
            }
        }

        for (int i = 0; i < triangles.Length; i++)
        {
            Debug.Log(triangles[i]);
        }

        //verts = new Vector3[]
        //{
        //    new Vector3(0, 0, 0),
        //    new Vector3(1, 0, 0),
        //    new Vector3(1, 0, 1),
        //    new Vector3(0, 0, 1),
        //};

        //triangles = new int[]{
        //    0, 1, 2,
        //    1, 3, 2
        //};

        mesh.Clear();

        mesh.vertices  = verts;
        mesh.uv        = uv;
        mesh.triangles = triangles;

        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        mesh.Optimize();
    }
示例#3
0
    private void CreateMesh(GameObject arcObject, EdgeCollider2D edgeCollider)
    {
        Logger.Info("Building meshes");

        var renderer = arcObject.AddComponent <MeshRenderer>();

        renderer.shadowCastingMode    = UnityEngine.Rendering.ShadowCastingMode.Off;
        renderer.receiveShadows       = false;
        renderer.useLightProbes       = false;
        renderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
        renderer.material             = fillMaterial;
        renderer.sortingLayerName     = "Platforms";

        var mf = arcObject.AddComponent <MeshFilter>();

        var mesh = new Mesh();

        mf.mesh = mesh;

        var vertices  = new List <Vector3>();
        var triangles = new List <int>();
        var normals   = new List <Vector3>();
        var uvs       = new List <Vector2>();

        var index = 0;


        float fillTo = meshBuilderFillDistanceType == MeshBuilderFillDistanceType.Relative
      ? fillDistance
      : meshBuilderFillType == MeshBuilderFillType.Horizontal
        ? (fillDistance - arcObject.transform.position.x)
        : (fillDistance - arcObject.transform.position.y);

        for (int i = 1; i < edgeCollider.points.Length; i++)
        {
            //vertices.Add(new Vector3(edgeCollider.points[i - 1].x, edgeCollider.points[i - 1].y, 0)); //top-left
            //vertices.Add(new Vector3(edgeCollider.points[i].x, edgeCollider.points[i].y, 0)); //top-right
            //vertices.Add(new Vector3(edgeCollider.points[i - 1].x, fillHeight, 0)); //bottom-left
            //vertices.Add(new Vector3(edgeCollider.points[i].x, fillHeight, 0)); //bottom-right

            if (meshBuilderFillType == MeshBuilderFillType.Vertical)
            {
                if (fillTo <= 0f)
                {
                    vertices.Add(new Vector3(edgeCollider.points[i - 1].x, edgeCollider.points[i - 1].y, 0)); //top-left
                    vertices.Add(new Vector3(edgeCollider.points[i].x, edgeCollider.points[i].y, 0));         //top-right
                    vertices.Add(new Vector3(edgeCollider.points[i - 1].x, fillTo, 0));                       //bottom-left
                    vertices.Add(new Vector3(edgeCollider.points[i].x, fillTo, 0));                           //bottom-right
                }
                else
                {
                    vertices.Add(new Vector3(edgeCollider.points[i - 1].x, fillTo, 0));                       //top-left
                    vertices.Add(new Vector3(edgeCollider.points[i].x, fillTo, 0));                           //top-right
                    vertices.Add(new Vector3(edgeCollider.points[i - 1].x, edgeCollider.points[i - 1].y, 0)); //bottom-left
                    vertices.Add(new Vector3(edgeCollider.points[i].x, edgeCollider.points[i].y, 0));         //bottom-right
                }
            }
            else
            {
                if (fillTo <= 0f)
                {
                    vertices.Add(new Vector3(fillTo, edgeCollider.points[i].y, 0));                           //top-left
                    vertices.Add(new Vector3(edgeCollider.points[i].x, edgeCollider.points[i].y, 0));         //top-right
                    vertices.Add(new Vector3(fillTo, edgeCollider.points[i - 1].y, 0));                       //bottom-left
                    vertices.Add(new Vector3(edgeCollider.points[i - 1].x, edgeCollider.points[i - 1].y, 0)); //bottom-right
                }
                else
                {
                    vertices.Add(new Vector3(edgeCollider.points[i].x, edgeCollider.points[i].y, 0));         //top-left
                    vertices.Add(new Vector3(fillTo, edgeCollider.points[i].y, 0));                           //top-right
                    vertices.Add(new Vector3(edgeCollider.points[i - 1].x, edgeCollider.points[i - 1].y, 0)); //bottom-left
                    vertices.Add(new Vector3(fillTo, edgeCollider.points[i - 1].y, 0));                       //bottom-right
                }
            }



            triangles.Add(index);
            triangles.Add(index + 1);
            triangles.Add(index + 2);
            triangles.Add(index + 3);
            triangles.Add(index + 2);
            triangles.Add(index + 1);

            index += 4;

            normals.Add(Vector3.forward);
            normals.Add(Vector3.forward);
            normals.Add(Vector3.forward);
            normals.Add(Vector3.forward);

            uvs.Add(new Vector2(0, 1)); //top-left
            uvs.Add(new Vector2(1, 1)); //top-right
            uvs.Add(new Vector2(0, 0)); //bottom-left
            uvs.Add(new Vector2(1, 0)); //bottom-right
        }

        mesh.vertices  = vertices.ToArray();
        mesh.normals   = normals.ToArray();
        mesh.triangles = triangles.ToArray();
        mesh.uv        = uvs.ToArray();
        mesh.RecalculateNormals();
    }
示例#4
0
    void loadJsonBodies(JSONNode jsonBodies)
    {
        int BodyCount = 0;

        for (int i = 0, numberOfBodies = jsonBodies.Count; i < numberOfBodies; i++)
        {
            JSONNode jsonBody = jsonBodies[i];

            int      bodyType        = jsonBody["type"].AsInt;
            JSONNode pos             = jsonBody["position"];
            Vector3  position        = new Vector3(pos[0].AsFloat / RATIO, -pos[1].AsFloat / RATIO, 0);
            float    rotation        = -jsonBody["rotation"].AsFloat;
            float    linearDamping   = jsonBody["linearDamping"].AsFloat;
            float    angularDamping  = jsonBody["angularDamping"].AsFloat;
            string   userData        = jsonBody["userData"].Value;
            bool     isFixedRotation = jsonBody["isFixedRotation"].AsBool;
            bool     isBullet        = jsonBody["isBullet"].AsBool;


            GameObject body = new GameObject(userData.Length > 0 ? userData : "body" + BodyCount++);
            body.transform.position = position;
            body.transform.rotation = Quaternion.Euler(0, 0, rotation);
            body.AddComponent <DebugRenderer>();

            float          density  = 0;
            List <Fixture> fixtures = loadJsonFixtures(jsonBody["fixtures"]);
            for (int j = 0, numberOfFixtures = fixtures.Count; j < numberOfFixtures; j++)
            {
                Fixture fixture = fixtures[j];
                density += fixture.density;
                if (fixture.shapeType == (int)ShapeTypes.SHAPE_BOX)
                {
                    BoxCollider2D boxCollider = body.AddComponent <BoxCollider2D>();
                    boxCollider.isTrigger      = fixture.isTrigger;
                    boxCollider.offset         = fixture.offset;
                    boxCollider.size           = fixture.size;
                    boxCollider.sharedMaterial = fixture.physicsMaterial;
                }
                else if (fixture.shapeType == (int)ShapeTypes.SHAPE_CIRCLE)
                {
                    CircleCollider2D circleCollider = body.AddComponent <CircleCollider2D>();
                    circleCollider.isTrigger      = fixture.isTrigger;
                    circleCollider.offset         = fixture.offset;
                    circleCollider.radius         = fixture.size.x;
                    circleCollider.sharedMaterial = fixture.physicsMaterial;
                }
                else if (fixture.shapeType == (int)ShapeTypes.SHAPE_POLYGON)
                {
                    PolygonCollider2D polyCollider = body.AddComponent <PolygonCollider2D>();
                    polyCollider.isTrigger = fixture.isTrigger;
                    polyCollider.offset    = fixture.offset;
                    polyCollider.SetPath(0, fixture.vertices);
                    polyCollider.sharedMaterial = fixture.physicsMaterial;
                }
                else if (fixture.shapeType == (int)ShapeTypes.SHAPE_CHAIN)
                {
                    EdgeCollider2D edgeCollider = body.AddComponent <EdgeCollider2D>();
                    edgeCollider.isTrigger      = fixture.isTrigger;
                    edgeCollider.offset         = fixture.offset;
                    edgeCollider.points         = fixture.vertices;
                    edgeCollider.sharedMaterial = fixture.physicsMaterial;
                }
            }

            body.AddComponent <Rigidbody2D>();
            Rigidbody2D rigidBody2D = body.GetComponent <Rigidbody2D>();
            rigidBody2D.isKinematic = bodyType == 1 || bodyType == 0;
            rigidBody2D.fixedAngle  = isFixedRotation;
            rigidBody2D.mass        = density;
            rigidBody2D.angularDrag = angularDamping;
            rigidBody2D.drag        = linearDamping;

            if (isBullet)
            {
                rigidBody2D.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
            }
            else
            {
                rigidBody2D.collisionDetectionMode = CollisionDetectionMode2D.None;
            }

            loadedObjects.Add(body);
        }
    }
    void BuildPhysicsMesh2D(EdgeCollider2D[] edgeColliders, int numEdgeColliders)
    {
        // Delete surplus
        for (int i = numEdgeColliders; i < edgeColliders.Length; ++i)
        {
#if UNITY_EDITOR
            DestroyImmediate(edgeColliders[i]);
#else
            Destroy(edgeColliders[i]);
#endif
        }

        Vector2[] boxPos = new Vector2[5];

        // Fill in missing, only do this if necessary
        if (numEdgeColliders > edgeColliders.Length)
        {
            EdgeCollider2D[] allEdgeColliders = new EdgeCollider2D[numEdgeColliders];
            int numToFill = Mathf.Min(numEdgeColliders, edgeColliders.Length);
            for (int i = 0; i < numToFill; ++i)
            {
                allEdgeColliders[i] = edgeColliders[i];
            }
            for (int i = numToFill; i < numEdgeColliders; ++i)
            {
                allEdgeColliders[i] = gameObject.AddComponent <EdgeCollider2D>();
            }
            edgeColliders = allEdgeColliders;
        }

        // second pass, build composite mesh
        Matrix4x4 scaleMatrix = Matrix4x4.identity;
        scaleMatrix.m00 = _scale.x;
        scaleMatrix.m11 = _scale.y;
        scaleMatrix.m22 = _scale.z;

        int currEdgeCollider = 0;
        foreach (tk2dBatchedSprite bs in batchedSprites)
        {
            if (!bs.IsDrawn)             // when the first non-drawn child is found, it signals the end of the drawn list
            {
                break;
            }

            tk2dSpriteDefinition spriteDef = bs.GetSpriteDefinition();

            bool    buildSpriteDefinitionMesh = false;
            bool    buildBox   = false;
            Vector3 boxOrigin  = Vector3.zero;
            Vector3 boxExtents = Vector3.zero;
            switch (bs.type)
            {
            case tk2dBatchedSprite.Type.Sprite:
                if (spriteDef != null && spriteDef.colliderType == tk2dSpriteDefinition.ColliderType.Mesh)
                {
                    buildSpriteDefinitionMesh = true;
                }
                if (spriteDef != null && spriteDef.colliderType == tk2dSpriteDefinition.ColliderType.Box)
                {
                    buildBox   = true;
                    boxOrigin  = spriteDef.colliderVertices[0];
                    boxExtents = spriteDef.colliderVertices[1];
                }
                break;

            case tk2dBatchedSprite.Type.ClippedSprite:
            case tk2dBatchedSprite.Type.SlicedSprite:
            case tk2dBatchedSprite.Type.TiledSprite:
                buildBox = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider);
                if (buildBox)
                {
                    boxOrigin  = bs.CachedBoundsCenter;
                    boxExtents = bs.CachedBoundsExtents;
                }
                break;

            case tk2dBatchedSprite.Type.TextMesh:
                break;
            }

            Matrix4x4 mat = scaleMatrix * bs.relativeMatrix;
            if (buildSpriteDefinitionMesh)
            {
                foreach (tk2dCollider2DData dat in spriteDef.edgeCollider2D)
                {
                    Vector2[] vertices = new Vector2[dat.points.Length];
                    for (int i = 0; i < dat.points.Length; ++i)
                    {
                        vertices[i] = mat.MultiplyPoint(dat.points[i]);
                    }
                    edgeColliders[currEdgeCollider].points = vertices;
                }

                foreach (tk2dCollider2DData dat in spriteDef.polygonCollider2D)
                {
                    Vector2[] vertices = new Vector2[dat.points.Length + 1];
                    for (int i = 0; i < dat.points.Length; ++i)
                    {
                        vertices[i] = mat.MultiplyPoint(dat.points[i]);
                    }
                    vertices[dat.points.Length]            = vertices[0];          // manual wrap around for poly collider
                    edgeColliders[currEdgeCollider].points = vertices;
                }

                currEdgeCollider++;
            }
            else if (buildBox)
            {
                Vector3 min = boxOrigin - boxExtents;
                Vector3 max = boxOrigin + boxExtents;
                boxPos[0] = mat.MultiplyPoint(new Vector2(min.x, min.y));
                boxPos[1] = mat.MultiplyPoint(new Vector2(max.x, min.y));
                boxPos[2] = mat.MultiplyPoint(new Vector2(max.x, max.y));
                boxPos[3] = mat.MultiplyPoint(new Vector2(min.x, max.y));
                boxPos[4] = boxPos[0];
                edgeColliders[currEdgeCollider].points = boxPos;
                currEdgeCollider++;
            }
        }
    }
        /// <summary>
        /// Create the mesh
        /// </summary>
        void Update()
        {
      #if UNITY_EDITOR
            OnValidate();
      #endif

            Mesh mesh = new Mesh();

            PolygonCollider2D _polygon2d = gameObject.GetComponent <PolygonCollider2D>();
            BoxCollider2D     _box2d     = gameObject.GetComponent <BoxCollider2D>();
            CircleCollider2D  _circle2d  = gameObject.GetComponent <CircleCollider2D>();
            EdgeCollider2D    _edge2d    = gameObject.GetComponent <EdgeCollider2D>();

            if (_polygon2d)
            {
                // points are alredy rotated :)
                int       pointCount = _polygon2d.GetTotalPointCount();
                Vector2[] points     = _polygon2d.points;

                Vector3[] vertices = new Vector3[pointCount];
                for (int j = 0; j < pointCount; j++)
                {
                    Vector2 actual = points[j];
                    vertices[j] = new Vector3(actual.x, actual.y, 0);
                }
                Triangulator tr        = new Triangulator(points);
                int[]        triangles = tr.Triangulate();
                mesh.vertices  = vertices;
                mesh.triangles = triangles;
            }

            if (_box2d)
            {
                mesh.vertices = GetBoxCorners(_box2d);
                int[] triangles = { 0, 1, 2, 1, 3, 2 };
                mesh.triangles = triangles;
            }

            if (_circle2d)
            {
                float scale = 1f / 16f;

                Vector3[] vertices = new Vector3[16];
                Vector2[] points   = new Vector2[16];
                for (int j = 0; j < 16; j++)
                {
                    float x = (_circle2d.offset.x +
                               Mathf.Cos(scale * j * 2 * Mathf.PI) * _circle2d.radius) *
                              _circle2d.transform.localScale.x;
                    float y = (_circle2d.offset.y +
                               Mathf.Sin(scale * j * 2 * Mathf.PI) * _circle2d.radius) *
                              _circle2d.transform.localScale.y;
                    points[j]   = new Vector2(x, y);
                    vertices[j] = new Vector3(x, y, 0);
                }
                Triangulator tr        = new Triangulator(points);
                int[]        triangles = tr.Triangulate();
                mesh.vertices  = vertices;
                mesh.triangles = triangles;
            }

            if (_edge2d)
            {
                Debug.LogWarning("EdgeCollider2D is not supported");
            }

            _mf.mesh = mesh;
        }
    private ContactInfo findContact(Vector2 movement)
    {
        Vector2 start = transform.position;
        Vector2 end   = (Vector2)transform.position + movement;

        Collider2D[] colliders = Physics2D.OverlapAreaAll(new Vector2(Mathf.Min(start.x, end.x) - 1, Mathf.Min(start.y, end.y) - 1),
                                                          new Vector2(Mathf.Max(start.x, end.x) + 1, Mathf.Max(start.y, end.y) + 1));

        float          minDistance = Mathf.Infinity;
        TrajectoryInfo minTi       = null;
        EdgeCollider2D minEdge     = null;
        int            minPoint    = -1;

        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].GetType() == typeof(EdgeCollider2D))
            {
                EdgeCollider2D edge = (EdgeCollider2D)colliders[i];

                for (int j = 0; j < edge.points.Length - 1; j++)
                {
                    bool canCollide = (contactCount < 1 || contactInfos[0].acceptableEdge(edge, j)) &&
                                      (contactCount < 2 || contactInfos[1].acceptableEdge(edge, j));
                    //&& tester != edge;

                    if (canCollide)
                    {
                        TrajectoryInfo ti = contactSolver.getFirstContact(start,
                                                                          end,
                                                                          edge.transform.TransformPoint(edge.points[j] + edge.offset),
                                                                          edge.transform.TransformPoint(edge.points[j + 1] + edge.offset),
                                                                          radius);

                        if (ti)
                        {
                            Vector2 tangent = edge.points[j + 1] - edge.points[j];
                            Vector2 normal  = new Vector2(-tangent.y, tangent.x);
                            if (edge.gameObject.tag != "OneWay" || (ti.side && Vector2.Dot(movement, normal) < 0))
                            {
                                float distance = Vector2.Distance(start, ti.getPosition());
                                if (distance < minDistance)
                                {
                                    minTi       = ti;
                                    minDistance = distance;
                                    minEdge     = edge;
                                    minPoint    = j;
                                }
                            }
                        }
                    }
                }
            }
        }

        if (minTi)
        {
            return(new ContactInfo(this,
                                   minTi.contactRatio,
                                   minEdge,
                                   minPoint,
                                   minTi.side,
                                   minTi.isEdgeContact,
                                   minTi.angle));
        }
        else
        {
            return(null);
        }
    }
示例#8
0
 // Used mostly in debugging to referesh the arcs from the editor
 // (see LoopArc Editor)
 public void EditorRefresh()
 {
     lineRenderer = GetComponent <LineRenderer> ();
     edgeCollider = GetComponent <EdgeCollider2D> ();
     RefreshArc();
 }
示例#9
0
 void Start()
 {
     edge = GetComponent <EdgeCollider2D>();
     Generate();
 }
示例#10
0
 protected virtual void CreateDefaultEdgeCollider2D()
 {
     m_EdgeCollider2D           = gameObject.AddComponent <EdgeCollider2D>();
     m_EdgeCollider2D.isTrigger = true;
 }
示例#11
0
    //
    // Object Methods
    //

    // make sure to draw the arc on spawn
    void Start()
    {
        lineRenderer = GetComponent <LineRenderer> ();
        edgeCollider = GetComponent <EdgeCollider2D> ();
        RefreshArc();
    }
示例#12
0
    protected virtual void Update()
    {
        if (GameController.wind_count && (Time.time - begin_time) > duration)
        {//风区持续时间到了
            DeleteLine();

            return;
        }
        if (GameController.wind_count)
        {//计时时不允许画画
            return;
        }

        if (can_draw_blue)
        {
            if (Input.GetMouseButtonDown(0))
            {
                is_draw_blue = true;
            }
        }


        if (!can_draw_blue)
        {
            return;
        }

        if (Input.GetMouseButtonUp(0) && is_draw_blue)
        {
            if (audioController.isPlaying == false)
            {
                //音效控制
                audioController.Stop();
            }
            can_draw_blue             = false;
            is_draw_blue              = false;
            GameController.wind_count = true; //风生效
            begin_time = Time.time;           //风生效的开始时间
            //Debug.Log("风生效的开始时间1");
            GameController.BlueLine_num += 1; //已画线条数加一
            wind_end = m_Camera.ScreenToWorldPoint(Input.mousePosition);
        }

        if (HadDrawDistance >= limit)
        {
            can_draw_blue             = false;
            is_draw_blue              = false;
            GameController.wind_count = true; //风生效
            begin_time = Time.time;           //风生效的开始时间
            //Debug.Log("风生效的开始时间2");
            GameController.BlueLine_num += 1; //已画线条数加一
            wind_end = m_Camera.ScreenToWorldPoint(Input.mousePosition);
            return;
        }

        if (Input.GetMouseButtonDown(0) && GameController.InkDistance > 0)//当鼠标按键按下时,返回一次true,后面参数0是左键,1是右键,2是中键
        {
            if (GameController.BlueLine_num == 1)
            {
                DeleteLine();
            }
            buffer   = Vector2.zero;              //初始化上一画点
            now      = Vector2.zero;              //初始化现在画点
            m_Points = new List <Vector2>();      //初始化一条新线
            //pos.Add(m_Points);                    //添加到线的数组


            m_line     = new GameObject("BlueDraw");  //创建新的物体作为画线
            m_line.tag = "Wind";
            /*****************************参数配置************************/
            /*-----------------------------------------------------------*/
            m_LineRenderer             = m_line.AddComponent <LineRenderer>();
            m_EdgeCollider2D           = m_line.AddComponent <EdgeCollider2D>();
            m_EdgeCollider2D.isTrigger = true;
            //Settings of the linerender component
            m_LineRenderer.positionCount = 0;           //Describe an array of Vector3 points to connect
            m_LineRenderer.material      = m_material;  //Line material
            m_LineRenderer.startColor    = Color.green; //The color of startpoint
            m_LineRenderer.endColor      = Color.green; //The color of endpoint
            m_LineRenderer.startWidth    = 0.5f;        //The width of startpoint
            m_LineRenderer.endWidth      = 0.5f;        //The width of endpoint
            m_LineRenderer.useWorldSpace = true;        //The points are considered as world space coordinates
            /*-----------------------------------------------------------*/

            wind_start = m_Camera.ScreenToWorldPoint(Input.mousePosition);
        }

        if (Input.GetMouseButton(0) && GameController.InkDistance > 0)//当鼠标按键按下时,返回true,可能多次,根据你鼠标按下的时间	,后面参数0是左键,1是右键,2是中键
        {
            if (audioController.isPlaying == false)
            {
                //音效控制
                audioController.PlayOneShot(drawWindAudio);
            }
            mouseposition = m_Camera.ScreenToWorldPoint(Input.mousePosition);
            if (buffer == Vector2.zero)
            {
                Vector2 mousePosition1 = mouseposition;
                buffer = mousePosition1;
                return;
            }
            else
            {
                now = mouseposition;
            }

            /****************射线检测需要关闭线自身的碰撞体*****************************/
            m_EdgeCollider2D.enabled = false;
            if (Hit = Physics2D.Linecast(buffer, now))
            {
                if (Hit.collider.tag != "Player" && Hit.collider.tag != "Boat" && Hit.collider.tag != "FirePosition" && Hit.collider.tag != "Light" && Hit.collider.tag != "Tree" && Hit.collider.tag != "Rope")
                {
                    return;
                }
            }
            m_EdgeCollider2D.enabled = true;

            /****************射线检测完需要开启线自身的碰撞体*****************************/
            if (now != Vector2.zero)
            {
                //计算两点之间距离
                Vector2 offset = now - buffer;
                bluedistance = offset.magnitude;
                //当剩余墨量大于需要画出的线段,并且不会超过560像素
                if (!m_Points.Contains(mouseposition) && (GameController.InkDistance - bluedistance) >= 0 && (bluedistance + HadDrawDistance) < limit)
                {
                    GameController.InkDistance = GameController.InkDistance - bluedistance;
                    HadDrawDistance           += bluedistance;//已经画了bluedistances的长度
                    m_Points.Add(mouseposition);
                    m_LineRenderer.positionCount = m_Points.Count;
                    m_LineRenderer.SetPosition(m_LineRenderer.positionCount - 1, mouseposition);
                    if (m_EdgeCollider2D != null && m_AddCollider && m_Points.Count > 1)
                    {
                        m_EdgeCollider2D.points = m_Points.ToArray();
                    }
                }
                else if (!m_Points.Contains(mouseposition) && (GameController.InkDistance - bluedistance) >= 0) //当剩余墨量大于需要画出的线段,并且超过560像素
                {
                    float   NowCanDraw = limit - HadDrawDistance;
                    Vector2 v          = offset.normalized;
                    Vector2 end        = buffer + v * NowCanDraw;
                    HadDrawDistance += NowCanDraw;
                    m_Points.Add(end);
                    m_LineRenderer.positionCount = m_Points.Count;
                    m_LineRenderer.SetPosition(m_LineRenderer.positionCount - 1, end);
                    if (m_EdgeCollider2D != null && m_AddCollider && m_Points.Count > 1)
                    {
                        m_EdgeCollider2D.points = m_Points.ToArray();
                    }
                    GameController.InkDistance -= NowCanDraw;
                }
                //当剩余墨量小于需要画出的线段
                else if (!m_Points.Contains(mouseposition) && (GameController.InkDistance - bluedistance) < 0)
                {
                    float NowCanDraw = limit - HadDrawDistance;
                    if (NowCanDraw > GameController.InkDistance)
                    {
                        Vector2 v   = offset.normalized;
                        Vector2 end = buffer + v * GameController.InkDistance;
                        HadDrawDistance += GameController.InkDistance;
                        m_Points.Add(end);
                        m_LineRenderer.positionCount = m_Points.Count;
                        m_LineRenderer.SetPosition(m_LineRenderer.positionCount - 1, end);
                        if (m_EdgeCollider2D != null && m_AddCollider && m_Points.Count > 1)
                        {
                            m_EdgeCollider2D.points = m_Points.ToArray();
                        }
                        GameController.InkDistance = 0;
                    }
                    else
                    {
                        Vector2 v   = offset.normalized;
                        Vector2 end = buffer + v * NowCanDraw;
                        HadDrawDistance += NowCanDraw;
                        m_Points.Add(end);
                        m_LineRenderer.positionCount = m_Points.Count;
                        m_LineRenderer.SetPosition(m_LineRenderer.positionCount - 1, end);
                        if (m_EdgeCollider2D != null && m_AddCollider && m_Points.Count > 1)
                        {
                            m_EdgeCollider2D.points = m_Points.ToArray();
                        }
                        GameController.InkDistance -= NowCanDraw;
                    }
                }
                buffer = now;
            }
        }
    }
示例#13
0
 public ObiEdgeMeshHandle GetOrCreateEdgeMesh(EdgeCollider2D collider)
 {
     return(edgeMeshContainer.GetOrCreateEdgeMesh(collider));
 }
 public void StopEditing()
 {
     m_ActiveCollider        = null;
     Undo.undoRedoPerformed -= UndoRedoPerformed;
 }
示例#15
0
 private void Awake()
 {
     collid = GetComponent <EdgeCollider2D>();
 }
示例#16
0
 private void OnDisable()
 {
     m_edge = null;
     m_poly = null;
 }
示例#17
0
    void OnDrawGizmos()
    {
        if (!Application.isPlaying)
        {
            boxColliders2D = (BoxCollider2D[])Resources.FindObjectsOfTypeAll(typeof(BoxCollider2D));
            boxPointList   = new Vector3[boxColliders2D.Length][];

            circleColliders2D = (CircleCollider2D[])Resources.FindObjectsOfTypeAll(typeof(CircleCollider2D));
            circlePointList   = new Vector3[circleColliders2D.Length][];

            polygonColliders2D = (PolygonCollider2D[])Resources.FindObjectsOfTypeAll(typeof(PolygonCollider2D));
            polygonPointList   = new Vector3[polygonColliders2D.Length][];

            edgeColliders2D = (EdgeCollider2D[])Resources.FindObjectsOfTypeAll(typeof(EdgeCollider2D));
            edgePointList   = new Vector3[edgeColliders2D.Length][];

            anchoredJoints2D       = (AnchoredJoint2D[])Resources.FindObjectsOfTypeAll(typeof(AnchoredJoint2D));
            anchoredJointPointList = new Vector3[anchoredJoints2D.Length][];

            for (int i = 0; i < boxColliders2D.Length; i++)
            {
                BoxCollider2D collider    = boxColliders2D [i];
                Vector3[]     boundPoints = GetBoxPoints(collider);
                boxPointList [i] = boundPoints;
            }

            for (int i = 0; i < circleColliders2D.Length; i++)
            {
                CircleCollider2D collider     = circleColliders2D [i];
                Vector3[]        circlePoints = GetCircleColliderPoints(collider, 40);
                circlePointList [i] = circlePoints;
            }

            for (int i = 0; i < polygonColliders2D.Length; i++)
            {
                PolygonCollider2D collider      = polygonColliders2D [i];
                Vector3[]         polygonPoints = GetPolygonPoints(collider);
                polygonPointList [i] = polygonPoints;
            }

            for (int i = 0; i < edgeColliders2D.Length; i++)
            {
                EdgeCollider2D collider   = edgeColliders2D [i];
                Vector3[]      edgePoints = GetEdgePoints(collider);
                edgePointList [i] = edgePoints;
            }

            for (int i = 0; i < anchoredJoints2D.Length; i++)
            {
                AnchoredJoint2D anchoredJoint       = anchoredJoints2D [i];
                Vector3[]       anchoredJointPoints = GetAnchoredJointPoints(anchoredJoint);
                anchoredJointPointList [i] = anchoredJointPoints;
            }

            DrawBox2DGizmo(boxPointList);
            DrawBox2DGizmo(circlePointList);
            DrawBox2DGizmo(polygonPointList);
            DrawBox2DGizmo(edgePointList);
            DrawBox2DGizmo(anchoredJointPointList);
        }
    }
示例#18
0
 private void Awake()
 {
     LineRenderer = GetComponent <LineRenderer>();
     EdgeCollider = GetComponent <EdgeCollider2D>();
 }
示例#19
0
    void DetectTrackBelow()
    {
        if (onTrack == false)
        {
            RaycastHit2D hit = Physics2D.Raycast(new Vector2(raycastOrigin.transform.position.x, raycastOrigin.transform.position.y), Vector2.down, raycastDistance, trackLayerMask);

            UnityEngine.Debug.DrawRay(raycastOrigin.transform.position, Vector3.down * raycastDistance, Color.blue);

            if (hit.collider != null)
            {
                if (hit.distance <= detectDistance && (hit.distance < prevHitDist && prevHitDist >= detectDistance))
                {
                    currentTrack = hit.collider.gameObject;

                    initialPosition = new Vector3(hit.point.x, hit.point.y, 0);

                    currentTrackEdgeCollider = currentTrack.GetComponent <EdgeCollider2D> ();

                    gameObject.transform.position = hit.point;

                    for (int i = 0; i < currentTrackEdgeCollider.pointCount; i++)
                    {
                        if (currentTrackEdgeCollider.points [i].x + currentTrack.transform.position.x >= hit.point.x)
                        {
                            currentPoint = currentTrackEdgeCollider.points [i];

                            currentPointIndex = i;

                            i = currentTrackEdgeCollider.pointCount;
                        }
                    }

                    currentDirection = (currentPoint - (initialPosition - currentTrack.transform.position)).normalized;

                    prevDirection = currentDirection;

                    transform.right = currentDirection;

                    SetOnTrack();

                    usingInitPos = true;

                    initPosLerpOffset = Vector3.Distance(initialPosition, currentPoint + currentTrack.transform.position) / curveVerticeDistance;

                    stopWatch.Start();
                }


                prevHitDist = hit.distance;
            }
            else
            {
                if (prevHitDist != 0)
                {
                    prevHitDist = 0;
                }
            }
        }
        else
        {
            if ((stopWatch.ElapsedMilliseconds / (moveSpeed * initPosLerpOffset)) >= 1)
            {
                if (usingInitPos)
                {
                    usingInitPos = false;

                    initPosLerpOffset = 1;
                }

                prevPoint = currentPoint;

                currentPointIndex++;

                if (currentPointIndex == currentTrackEdgeCollider.pointCount)
                {
                    currentPointIndex = 1;

                    if (currentTrack.GetComponent <CurveInfo>().nextTrackPiece != null)
                    {
                        currentTrack = currentTrack.GetComponent <CurveInfo> ().nextTrackPiece;

                        currentTrackEdgeCollider = currentTrack.GetComponent <EdgeCollider2D> ();

                        currentPoint = currentTrackEdgeCollider.points [currentPointIndex];

                        prevPoint = currentTrackEdgeCollider.points [0];
                    }
                    else
                    {
                        SetOffTrack();
                    }
                }

                currentPoint = currentTrackEdgeCollider.points [currentPointIndex];

                prevDirection = currentDirection;

                currentDirection = (currentPoint - prevPoint).normalized;

                stopWatch.Reset();
                stopWatch.Start();
            }

            transform.right = Vector3.Lerp(prevDirection, currentDirection, stopWatch.ElapsedMilliseconds / moveSpeed);

            if (usingInitPos)
            {
                gameObject.transform.position = Vector3.Lerp(initialPosition, currentPoint + currentTrack.transform.position, (stopWatch.ElapsedMilliseconds / (moveSpeed * initPosLerpOffset)));
            }
            else
            {
                gameObject.transform.position = Vector3.Lerp(prevPoint + currentTrack.transform.position, currentPoint + currentTrack.transform.position, stopWatch.ElapsedMilliseconds / moveSpeed);
            }
        }
    }
示例#20
0
        public static void Import(UTiledImportSettings settings)
        {
            String    mapFilename = settings.MapFilename;
            XDocument input       = XDocument.Load(mapFilename);

            String mapDirectory  = Path.GetDirectoryName(mapFilename) + "/" + Path.GetFileNameWithoutExtension(mapFilename);
            String meshDirectory = mapDirectory + "/" + "meshes";
            String matDirectory  = mapDirectory + "/" + "materials";

            if (!Directory.Exists(mapDirectory))
            {
                Directory.CreateDirectory(mapDirectory);
            }
            if (!Directory.Exists(meshDirectory))
            {
                Directory.CreateDirectory(meshDirectory);
            }
            if (!Directory.Exists(matDirectory))
            {
                Directory.CreateDirectory(matDirectory);
            }

            MapOrientation mapOrientation = MapOrientation.Unknown;

            switch (input.Document.Root.Attribute("orientation").Value)
            {
            case "orthogonal":
                mapOrientation = MapOrientation.Orthogonal;
                break;

            case "isometric":
                mapOrientation = MapOrientation.Isometric;
                break;

            case "staggered":
                mapOrientation = MapOrientation.Staggered;
                break;

            default:
                mapOrientation = MapOrientation.Unknown;
                break;
            }

            if (mapOrientation != MapOrientation.Orthogonal)
            {
                throw new NotSupportedException("UTiled supports only orthogonal maps");
            }

            String mapName       = Path.GetFileNameWithoutExtension(mapFilename);
            Int32  mapWidth      = Convert.ToInt32(input.Document.Root.Attribute("width").Value);
            Int32  mapHeight     = Convert.ToInt32(input.Document.Root.Attribute("height").Value);
            Int32  mapTileWidth  = Convert.ToInt32(input.Document.Root.Attribute("tilewidth").Value);
            Int32  mapTileHeight = Convert.ToInt32(input.Document.Root.Attribute("tileheight").Value);

            Dictionary <UInt32, SourceData>             gid2sprite  = new Dictionary <UInt32, SourceData>();
            Dictionary <String, List <UTiledProperty> > spriteprops = new Dictionary <string, List <UTiledProperty> >();
            List <String> imageList = new List <string>();

            GameObject mapGameObject = new GameObject();

            mapGameObject.name = mapName;

            if (input.Document.Root.Element("properties") != null)
            {
                UTiledProperties props = mapGameObject.AddComponent <UTiledProperties>();
                foreach (var pElem in input.Document.Root.Element("properties").Elements("property"))
                {
                    props.Add(pElem.Attribute("name").Value, pElem.Attribute("value").Value);
                }
            }

            Int32 tsNum = 1;

            foreach (var elem in input.Document.Root.Elements("tileset"))
            {
                UInt32   FirstGID = Convert.ToUInt32(elem.Attribute("firstgid").Value);
                XElement tsElem   = elem;

                if (elem.Attribute("source") != null)
                {
                    XDocument tsx = XDocument.Load(Path.Combine(Path.GetDirectoryName(mapFilename), elem.Attribute("source").Value));
                    tsElem = tsx.Root;
                }

                List <UTiledProperty> tilesetProps = new List <UTiledProperty>();
                if (tsElem.Element("properties") != null)
                {
                    foreach (var pElem in tsElem.Element("properties").Elements("property"))
                    {
                        tilesetProps.Add(new UTiledProperty()
                        {
                            Name = pElem.Attribute("name").Value, Value = pElem.Attribute("value").Value
                        });
                    }
                }

                Int32 tsTileWidth  = tsElem.Attribute("tilewidth") == null ? 0 : Convert.ToInt32(tsElem.Attribute("tilewidth").Value);
                Int32 tsTileHeight = tsElem.Attribute("tileheight") == null ? 0 : Convert.ToInt32(tsElem.Attribute("tileheight").Value);
                Int32 tsSpacing    = tsElem.Attribute("spacing") == null ? 0 : Convert.ToInt32(tsElem.Attribute("spacing").Value);
                Int32 tsMargin     = tsElem.Attribute("margin") == null ? 0 : Convert.ToInt32(tsElem.Attribute("margin").Value);

                Int32 tsTileOffsetX = 0;
                Int32 tsTileOffsetY = 0;
                if (tsElem.Element("tileoffset") != null)
                {
                    tsTileOffsetX = Convert.ToInt32(tsElem.Element("tileoffset").Attribute("x").Value);
                    tsTileOffsetY = Convert.ToInt32(tsElem.Element("tileoffset").Attribute("y").Value);
                }

                if (tsElem.Element("image") != null)
                {
                    XElement imgElem         = tsElem.Element("image");
                    String   tsImageFileName = Path.Combine(Path.GetDirectoryName(mapFilename), imgElem.Attribute("source").Value);

                    if (!File.Exists(tsImageFileName))
                    {
                        throw new Exception("Cannot find referenced tilesheet: " + tsImageFileName);
                    }

                    if (!imageList.Contains(tsImageFileName))
                    {
                        imageList.Add(tsImageFileName);
                    }

                    TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(tsImageFileName);
                    importer.textureType         = TextureImporterType.Sprite;
                    importer.spriteImportMode    = SpriteImportMode.Multiple;
                    importer.filterMode          = FilterMode.Point;
                    importer.spritePixelsToUnits = settings.PixelsPerUnit;

                    // Reflection Hack because this is a private method to get the non scaled size of the texture
                    object[] args = new object[2] {
                        0, 0
                    };
                    MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
                    mi.Invoke(importer, args);
                    Int32 tsImageWidth  = (int)args[0];
                    Int32 tsImageHeight = (int)args[1];
                    // yea, it's lame and should be a public method - vote for it here:
                    // http://feedback.unity3d.com/suggestions/get-original-width-and-height-of

                    List <SpriteMetaData> spritesmeta = new List <SpriteMetaData>(importer.spritesheet);
                    UInt32 gid = FirstGID;

                    for (int y = tsImageHeight - tsTileHeight - tsMargin; y >= tsMargin; y -= tsTileHeight + tsSpacing)
                    {
                        for (int x = tsMargin; x < tsImageWidth - tsMargin; x += tsTileWidth + tsSpacing)
                        {
                            if (x + tsTileWidth > tsImageWidth - tsMargin)
                            {
                                continue;
                            }

                            SpriteMetaData s = new SpriteMetaData();
                            s.name      = String.Format(String.Format("{0}_{1}_{2}", Path.GetFileNameWithoutExtension(mapFilename), tsNum, gid));
                            s.rect      = new Rect(x, y, tsTileWidth, tsTileHeight);
                            s.pivot     = new Vector2(tsTileWidth / 2, tsTileHeight / 2);
                            s.alignment = 0;

                            if (tilesetProps.Count > 0)
                            {
                                spriteprops[s.name] = new List <UTiledProperty>();
                                foreach (var item in tilesetProps)
                                {
                                    spriteprops[s.name].Add(item);
                                }
                            }

                            if (spritesmeta.Any(sx => sx.name.Equals(s.name)))
                            {
                                spritesmeta.RemoveAll(sx => sx.name.Equals(s.name));
                            }

                            spritesmeta.Add(s);
                            gid2sprite[gid] = new SourceData()
                            {
                                textureSize = new Vector2(tsImageWidth, tsImageHeight),
                                offsetX     = tsTileOffsetX,
                                offsetY     = tsTileOffsetY,
                                spriteName  = s.name,
                            };
                            gid++;
                        }
                    }

                    foreach (var tileElem in tsElem.Elements("tile"))
                    {
                        UInt32 id         = Convert.ToUInt32(tileElem.Attribute("id").Value);
                        String spriteName = String.Format(String.Format("{0}_{1}_{2}", Path.GetFileNameWithoutExtension(mapFilename), tsNum, id + FirstGID));
                        if (tileElem.Element("properties") != null)
                        {
                            if (!spriteprops.ContainsKey(spriteName))
                            {
                                spriteprops[spriteName] = new List <UTiledProperty>();
                            }

                            foreach (var pElem in tileElem.Element("properties").Elements("property"))
                            {
                                spriteprops[spriteName].Add(new UTiledProperty()
                                {
                                    Name = pElem.Attribute("name").Value, Value = pElem.Attribute("value").Value
                                });
                            }
                        }
                    }

                    importer.spritesheet = spritesmeta.ToArray();
                    AssetDatabase.WriteImportSettingsIfDirty(tsImageFileName);
                    AssetDatabase.LoadAssetAtPath(tsImageFileName, typeof(Texture2D));
                    AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
                }

                tsNum++;
            }

            List <UnityEngine.Object> sprites = new List <UnityEngine.Object>();

            foreach (var tsImageFileName in imageList)
            {
                sprites.AddRange(AssetDatabase.LoadAllAssetRepresentationsAtPath(tsImageFileName));
            }

            Int32 lCount    = 1;
            Int32 olCount   = 1;
            Int32 sortOrder = 1;
            float xoff      = mapWidth * mapTileWidth - mapWidth * mapTileWidth / 2;
            float yoff      = mapHeight * mapTileHeight - mapHeight * mapTileHeight / 2 + mapTileHeight;

            foreach (var lElem in input.Document.Root.Elements())
            {
                if (lElem.Name.LocalName.Equals("layer"))
                {
                    bool importMesh      = false;
                    bool importCollision = false;

                    if (settings.TileLayerSettings.Length >= lCount)
                    {
                        importCollision = settings.TileLayerSettings[lCount - 1].GenerateCollisionMesh;
                        importMesh      = settings.TileLayerSettings[lCount - 1].GenerateRenderMesh;
                    }

                    if (!importMesh && !importCollision)
                    {
                        lCount++;
                        continue;
                    }

                    GameObject layerGameObject = new GameObject();
                    layerGameObject.transform.parent = mapGameObject.transform;

                    layerGameObject.name = lElem.Attribute("name") == null ? "Unnamed" : lElem.Attribute("name").Value;
                    float layerOpacity = lElem.Attribute("opacity") == null ? 1.0f : Convert.ToSingle(lElem.Attribute("opacity").Value);
                    bool  layerVisible = lElem.Attribute("visible") == null ? true : lElem.Attribute("visible").Equals("1");

                    // LD29 specific
                    if (layerGameObject.name == "Overworld")
                    {
                        layerGameObject.AddComponent <TileLayerFader>();
                    }
                    else if (layerGameObject.name == "Overworld Objects" || layerGameObject.name == "Underworld Objects")
                    {
                        layerGameObject.AddComponent <ObjectLayerFader>();
                    }
                    // ----------

                    UTiledLayerSettings layerSettings = layerGameObject.AddComponent <UTiledLayerSettings>();
                    layerSettings.sortingOrder = sortOrder;
                    layerSettings.opacity      = layerOpacity;

                    EditorUtility.DisplayProgressBar("UTiled", "Generating Prefabs for " + settings.TileLayerSettings[lCount - 1].LayerName, (float)(lCount - 1) / settings.TileLayerSettings.Length);

                    if (lElem.Element("properties") != null)
                    {
                        UTiledProperties props = layerGameObject.AddComponent <UTiledProperties>();
                        foreach (var pElem in lElem.Element("properties").Elements("property"))
                        {
                            props.Add(pElem.Attribute("name").Value, pElem.Attribute("value").Value);
                        }
                    }

                    if (lElem.Element("data") != null)
                    {
                        List <UInt32> gids = new List <UInt32>();
                        if (lElem.Element("data").Attribute("encoding") != null || lElem.Element("data").Attribute("compression") != null)
                        {
                            // parse csv formatted data
                            if (lElem.Element("data").Attribute("encoding") != null && lElem.Element("data").Attribute("encoding").Value.Equals("csv"))
                            {
                                foreach (var gid in lElem.Element("data").Value.Split(",\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                                {
                                    gids.Add(Convert.ToUInt32(gid));
                                }
                            }
                            else if (lElem.Element("data").Attribute("encoding") != null && lElem.Element("data").Attribute("encoding").Value.Equals("base64"))
                            {
                                Byte[] data = Convert.FromBase64String(lElem.Element("data").Value);

                                if (lElem.Element("data").Attribute("compression") == null)
                                {
                                    // uncompressed data
                                    for (int i = 0; i < data.Length; i += sizeof(UInt32))
                                    {
                                        gids.Add(BitConverter.ToUInt32(data, i));
                                    }
                                }
                                else
                                {
                                    throw new NotSupportedException(String.Format("Compression '{0}' not supported.", lElem.Element("data").Attribute("compression").Value));
                                }
                            }
                            else
                            {
                                throw new NotSupportedException(String.Format("Encoding '{0}' not supported.  UTiled supports csv or base64", lElem.Element("data").Attribute("encoding").Value));
                            }
                        }
                        else
                        {
                            // parse xml formatted data
                            foreach (var tElem in lElem.Element("data").Elements("tile"))
                            {
                                gids.Add(Convert.ToUInt32(tElem.Attribute("gid").Value));
                            }
                        }

                        List <MeshData> meshes = new List <MeshData>();
                        for (int i = 0; i < gids.Count; i++)
                        {
                            UInt32 ID = gids[i] & ~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG);

                            if (ID > 0)
                            {
                                SourceData sd      = gid2sprite[ID];
                                Sprite     source  = (Sprite)sprites.First(s => s.name.Equals(sd.spriteName));
                                String     texFile = AssetDatabase.GetAssetPath(source.texture);

                                Boolean tdFlipHorizontally = Convert.ToBoolean(gids[i] & FLIPPED_HORIZONTALLY_FLAG);
                                Boolean tdFlipVertically   = Convert.ToBoolean(gids[i] & FLIPPED_VERTICALLY_FLAG);
                                Boolean tdFlipDiagonally   = Convert.ToBoolean(gids[i] & FLIPPED_DIAGONALLY_FLAG);

                                Int32 meshId = 0;
                                if (meshes.Any(m => m.materialName.Equals(texFile)))
                                {
                                    meshId = meshes.IndexOf(meshes.First(x => x.materialName.Equals(texFile)));
                                }
                                else
                                {
                                    meshes.Add(new MeshData()
                                    {
                                        materialName = texFile
                                    });
                                    meshId = meshes.Count - 1;
                                }

                                int triStart = meshes[meshId].verts.Count;
                                meshes[meshId].tris.AddRange(new int[] { triStart, triStart + 1, triStart + 2, triStart + 2, triStart + 3, triStart });

                                for (int j = 0; j < 4; j++)
                                {
                                    meshes[meshId].norms.Add(new Vector3(0, 0, -1));
                                }

                                if (mapOrientation == MapOrientation.Orthogonal)
                                {
                                    float x = i % mapWidth;
                                    float y = mapHeight - Mathf.Floor(i / mapWidth) - 1;

                                    Rect colLoc = new Rect(
                                        (x * mapTileWidth - xoff) / settings.PixelsPerUnit,
                                        (y * mapTileHeight + mapTileHeight - yoff) / settings.PixelsPerUnit,
                                        (float)mapTileWidth / settings.PixelsPerUnit,
                                        (float)mapTileHeight / settings.PixelsPerUnit
                                        );

                                    meshes[meshId].colverts.Add(new Vector3(colLoc.xMin, colLoc.yMax, 0));
                                    meshes[meshId].colverts.Add(new Vector3(colLoc.xMax, colLoc.yMax, 0));
                                    meshes[meshId].colverts.Add(new Vector3(colLoc.xMax, colLoc.yMin, 0));
                                    meshes[meshId].colverts.Add(new Vector3(colLoc.xMin, colLoc.yMin, 0));

                                    Vector3[] loc = new Vector3[] {
                                        new Vector3((x * mapTileWidth - xoff + sd.offsetX) / settings.PixelsPerUnit, (y * mapTileHeight + mapTileHeight - yoff + sd.offsetY + source.rect.height * sd.textureSize.y / source.texture.height) / settings.PixelsPerUnit),
                                        new Vector3((x * mapTileWidth - xoff + sd.offsetX + source.rect.width * sd.textureSize.x / source.texture.width) / settings.PixelsPerUnit, (y * mapTileHeight + mapTileHeight - yoff + sd.offsetY + source.rect.height * sd.textureSize.y / source.texture.height) / settings.PixelsPerUnit),
                                        new Vector3((x * mapTileWidth - xoff + sd.offsetX + source.rect.width * sd.textureSize.x / source.texture.width) / settings.PixelsPerUnit, (y * mapTileHeight + mapTileHeight - yoff + sd.offsetY) / settings.PixelsPerUnit),
                                        new Vector3((x * mapTileWidth - xoff + sd.offsetX) / settings.PixelsPerUnit, (y * mapTileHeight + mapTileHeight - yoff + sd.offsetY) / settings.PixelsPerUnit)
                                    };

                                    if (tdFlipDiagonally)
                                    {
                                        Vector3 pivot = new Vector3(loc[0].x + (loc[1].x - loc[0].x) / 2, loc[0].y + (loc[3].y - loc[0].y) / 2);
                                        for (int j = 0; j < loc.Length; j++)
                                        {
                                            Vector3 direction = pivot - loc[j];
                                            direction = Quaternion.Euler(new Vector3(0, 0, -90)) * direction;
                                            loc[j]    = direction + pivot;
                                        }
                                        tdFlipVertically = !tdFlipVertically;
                                    }
                                    if (tdFlipHorizontally)
                                    {
                                        Vector3 temp = loc[0];
                                        loc[0] = loc[1];
                                        loc[1] = temp;

                                        temp   = loc[3];
                                        loc[3] = loc[2];
                                        loc[2] = temp;
                                    }
                                    if (tdFlipVertically)
                                    {
                                        Vector3 temp = loc[0];
                                        loc[0] = loc[3];
                                        loc[3] = temp;

                                        temp   = loc[1];
                                        loc[1] = loc[2];
                                        loc[2] = temp;
                                    }

                                    meshes[meshId].verts.AddRange(loc);
                                }

                                Rect uvRect = new Rect(
                                    source.rect.x / source.texture.width,
                                    source.rect.y / source.texture.height,
                                    source.rect.width / source.texture.width,
                                    source.rect.height / source.texture.height
                                    );

                                meshes[meshId].uvs.AddRange(new Vector2[] {
                                    new Vector2(uvRect.xMin, uvRect.yMax),
                                    new Vector2(uvRect.xMax, uvRect.yMax),
                                    new Vector2(uvRect.xMax, uvRect.yMin),
                                    new Vector2(uvRect.xMin, uvRect.yMin)
                                });
                            }
                        }
                        List <MeshData> collMesh = new List <MeshData>();
                        collMesh.Add(new MeshData());
                        Int32 currentColMesh = 0;

                        for (int i = 0; i < meshes.Count; i++)
                        {
                            String   spriteMatFileName = String.Format("{0}/{1}-{2}.mat", matDirectory, layerGameObject.name, Path.GetFileNameWithoutExtension(meshes[i].materialName));
                            Material spriteMat         = (Material)AssetDatabase.LoadAssetAtPath(spriteMatFileName, typeof(Material));

                            if (importMesh)
                            {
                                if (spriteMat == null)
                                {
                                    spriteMat = new Material(Shader.Find("Sprites/Default"));
                                    spriteMat.SetFloat("PixelSnap", 1);
                                    spriteMat.EnableKeyword("PIXELSNAP_ON");
                                    spriteMat.color       = new Color(1, 1, 1, layerOpacity);
                                    spriteMat.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(meshes[i].materialName, typeof(Texture2D));
                                    AssetDatabase.CreateAsset(spriteMat, spriteMatFileName);
                                }
                                else
                                {
                                    spriteMat.SetFloat("PixelSnap", 1);
                                    spriteMat.EnableKeyword("PIXELSNAP_ON");
                                    spriteMat.color       = new Color(1, 1, 1, layerOpacity);
                                    spriteMat.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(meshes[i].materialName, typeof(Texture2D));
                                    EditorUtility.SetDirty(spriteMat);
                                }
                            }

                            if (importCollision)
                            {
                                for (int j = 0; j < meshes[i].colverts.Count; j += 4)
                                {
                                    if (collMesh[currentColMesh].colverts.Count >= 64997)
                                    {
                                        collMesh.Add(new MeshData());
                                        currentColMesh++;
                                    }

                                    Int32 v1, v2, v3, v4;
                                    v1 = FindVertIndex(meshes[i].colverts[j], collMesh[currentColMesh].colverts);
                                    if (v1 == -1)
                                    {
                                        collMesh[currentColMesh].colverts.Add(meshes[i].colverts[j]);
                                        collMesh[currentColMesh].norms.Add(meshes[i].norms[j]);
                                        collMesh[currentColMesh].uvs.Add(meshes[i].uvs[j]);
                                        v1 = collMesh[currentColMesh].colverts.Count - 1;
                                    }

                                    v2 = FindVertIndex(meshes[i].colverts[j + 1], collMesh[currentColMesh].colverts);
                                    if (v2 == -1)
                                    {
                                        collMesh[currentColMesh].colverts.Add(meshes[i].colverts[j + 1]);
                                        collMesh[currentColMesh].norms.Add(meshes[i].norms[j + 1]);
                                        collMesh[currentColMesh].uvs.Add(meshes[i].uvs[j + 1]);
                                        v2 = collMesh[currentColMesh].colverts.Count - 1;
                                    }

                                    v3 = FindVertIndex(meshes[i].colverts[j + 2], collMesh[currentColMesh].colverts);
                                    if (v3 == -1)
                                    {
                                        collMesh[currentColMesh].colverts.Add(meshes[i].colverts[j + 2]);
                                        collMesh[currentColMesh].norms.Add(meshes[i].norms[j + 2]);
                                        collMesh[currentColMesh].uvs.Add(meshes[i].uvs[j + 2]);
                                        v3 = collMesh[currentColMesh].colverts.Count - 1;
                                    }

                                    v4 = FindVertIndex(meshes[i].colverts[j + 3], collMesh[currentColMesh].colverts);
                                    if (v4 == -1)
                                    {
                                        collMesh[currentColMesh].colverts.Add(meshes[i].colverts[j + 3]);
                                        collMesh[currentColMesh].norms.Add(meshes[i].norms[j + 3]);
                                        collMesh[currentColMesh].uvs.Add(meshes[i].uvs[j + 3]);
                                        v4 = collMesh[currentColMesh].colverts.Count - 1;
                                    }

                                    collMesh[currentColMesh].tris.AddRange(new int[] { v1, v2, v3, v3, v4, v1 });
                                }
                            }

                            if (importMesh)
                            {
                                int totalMeshReq = Convert.ToInt32(Mathf.Ceil((float)meshes[i].verts.Count / 65000f));
                                for (int j = 0; j < totalMeshReq; j++)
                                {
                                    var verts = meshes[i].verts.Skip(j * 65000).Take(65000).ToArray();
                                    var tris  = meshes[i].tris.Skip(j * 97500).Take(97500).Select(t => t - j * 65000).ToArray();
                                    var norms = meshes[i].norms.Skip(j * 65000).Take(65000).ToArray();
                                    var uvs   = meshes[i].uvs.Skip(j * 65000).Take(65000).ToArray();

                                    GameObject layerMeshObject = new GameObject();
                                    layerMeshObject.transform.parent = layerGameObject.transform;
                                    layerMeshObject.name             = String.Format("{0} - {1}", Path.GetFileNameWithoutExtension(meshes[i].materialName), j + 1);

                                    MeshFilter   filter   = layerMeshObject.AddComponent <MeshFilter>();
                                    MeshRenderer renderer = layerMeshObject.AddComponent <MeshRenderer>();

                                    renderer.sortingOrder   = sortOrder;
                                    renderer.sharedMaterial = spriteMat;
                                    renderer.castShadows    = false;
                                    renderer.receiveShadows = false;

                                    String meshFileName = String.Format("{0}/{1}-{2}-{3}-{4}-{5}.asset", meshDirectory, layerGameObject.name,
                                                                        Path.GetFileNameWithoutExtension(meshes[i].materialName), lCount, i + 1, j + 1);
                                    Mesh mesh = (Mesh)AssetDatabase.LoadAssetAtPath(meshFileName, typeof(Mesh));
                                    if (mesh == null)
                                    {
                                        mesh = new Mesh()
                                        {
                                            vertices  = verts,
                                            triangles = tris,
                                            normals   = norms,
                                            uv        = uvs,
                                        };
                                        AssetDatabase.CreateAsset(mesh, meshFileName);
                                    }
                                    else
                                    {
                                        mesh.Clear(false);
                                        mesh.vertices  = verts;
                                        mesh.triangles = tris;
                                        mesh.normals   = norms;
                                        mesh.uv        = uvs;
                                        EditorUtility.SetDirty(mesh);
                                    }

                                    filter.mesh = mesh;
                                }
                            }
                        }

                        if (importCollision)
                        {
                            for (int i = 0; i < collMesh.Count; i++)
                            {
                                GameObject layerColMeshObject = new GameObject();
                                layerColMeshObject.transform.parent = layerGameObject.transform;
                                layerColMeshObject.name             = String.Format("Collision Mesh - {0}", i + 1);

                                MeshFilter   colFilter = layerColMeshObject.AddComponent <MeshFilter>();
                                MeshCollider collider  = layerColMeshObject.AddComponent <MeshCollider>();

                                String colMeshFileName = String.Format("{0}/{1}-{2}-{3}-collision.asset", meshDirectory, layerGameObject.name, lCount, i + 1);
                                Mesh   colMesh         = (Mesh)AssetDatabase.LoadAssetAtPath(colMeshFileName, typeof(Mesh));

                                if (colMesh == null)
                                {
                                    colMesh = new Mesh()
                                    {
                                        vertices  = collMesh[i].colverts.ToArray(),
                                        triangles = collMesh[i].tris.ToArray(),
                                        normals   = collMesh[i].norms.ToArray(),
                                        uv        = collMesh[i].uvs.ToArray(),
                                    };
                                    AssetDatabase.CreateAsset(colMesh, colMeshFileName);
                                }
                                else
                                {
                                    colMesh.Clear(false);
                                    colMesh.vertices  = collMesh[i].colverts.ToArray();
                                    colMesh.triangles = collMesh[i].tris.ToArray();
                                    colMesh.normals   = collMesh[i].norms.ToArray();
                                    colMesh.uv        = collMesh[i].uvs.ToArray();
                                    EditorUtility.SetDirty(colMesh);
                                }

                                colFilter.mesh      = colMesh;
                                collider.sharedMesh = colMesh;
                            }
                        }
                    }

                    layerGameObject.SetActive(layerVisible);
                    AssetDatabase.SaveAssets();
                    lCount++;
                    sortOrder++;
                }
                else if (lElem.Name.LocalName.Equals("objectgroup"))
                {
                    bool importlayer = false;

                    if (settings.ObjectLayerSettings.Length >= olCount)
                    {
                        importlayer = settings.ObjectLayerSettings[olCount - 1].ImportLayer;
                    }

                    if (!importlayer)
                    {
                        olCount++;
                        continue;
                    }

                    GameObject layerGameObject = new GameObject();
                    layerGameObject.transform.parent = mapGameObject.transform;

                    layerGameObject.name = lElem.Attribute("name") == null ? "Unnamed" : lElem.Attribute("name").Value;
                    float  layerOpacity = lElem.Attribute("opacity") == null ? 1.0f : Convert.ToSingle(lElem.Attribute("opacity").Value);
                    bool   layerVisible = lElem.Attribute("visible") == null ? true : lElem.Attribute("visible").Equals("1");
                    string layerColor   = lElem.Attribute("color") == null ? "#a0a0a4" : lElem.Attribute("color").Value; // #a0a0a4 is Tiled's default grey, but won't be in the file unless manually set

                    // LD29 specific
                    if (layerGameObject.name == "Overworld")
                    {
                        layerGameObject.AddComponent <TileLayerFader>();
                    }
                    else if (layerGameObject.name == "Overworld Objects" || layerGameObject.name == "Underworld Objects")
                    {
                        layerGameObject.AddComponent <ObjectLayerFader>();
                    }
                    // ----------

                    layerGameObject.SetActive(layerVisible);

                    UTiledLayerSettings layerSettings = layerGameObject.AddComponent <UTiledLayerSettings>();
                    layerSettings.opacity      = layerOpacity;
                    layerSettings.sortingOrder = sortOrder;

                    if (lElem.Element("properties") != null)
                    {
                        UTiledProperties props = layerGameObject.AddComponent <UTiledProperties>();
                        foreach (var pElem in lElem.Element("properties").Elements("property"))
                        {
                            props.Add(pElem.Attribute("name").Value, pElem.Attribute("value").Value);
                        }
                    }

                    foreach (var oElem in lElem.Elements("object"))
                    {
                        string oName    = oElem.Attribute("name") == null ? "Unnamed" : oElem.Attribute("name").Value;
                        string oType    = oElem.Attribute("type") == null ? null : oElem.Attribute("type").Value;
                        float? oX       = oElem.Attribute("x") == null ? null : (float?)Convert.ToSingle(oElem.Attribute("x").Value);
                        float? oY       = oElem.Attribute("y") == null ? null : (float?)Convert.ToSingle(oElem.Attribute("y").Value);
                        float? oWidth   = oElem.Attribute("width") == null ? null : (float?)Convert.ToSingle(oElem.Attribute("width").Value);
                        float? oHeight  = oElem.Attribute("height") == null ? null : (float?)Convert.ToSingle(oElem.Attribute("height").Value);
                        uint?  tileGID  = oElem.Attribute("gid") == null ? null : (uint?)Convert.ToUInt32(oElem.Attribute("gid").Value);
                        bool   oVisible = oElem.Attribute("visible") == null ? true : oElem.Attribute("visible").Equals("1");

                        GameObject obj = new GameObject();
                        obj.transform.parent = layerGameObject.transform;
                        obj.name             = oName;
                        obj.SetActive(oVisible);

                        if (oElem.Element("properties") != null || oType != null)
                        {
                            UTiledProperties props = obj.AddComponent <UTiledProperties>();

                            if (oElem.Element("properties") != null)
                            {
                                foreach (var pElem in oElem.Element("properties").Elements("property"))
                                {
                                    props.Add(pElem.Attribute("name").Value, pElem.Attribute("value").Value);
                                }
                            }

                            if (oType != null)
                            {
                                props.ObjectType = oType;
                            }
                        }

                        if (oElem.Element("ellipse") != null && oX.HasValue && oY.HasValue && oWidth.HasValue && oHeight.HasValue)
                        {
                            obj.AddComponent <CircleCollider2D>();
                            obj.transform.localScale    = new Vector3(oWidth.Value / settings.PixelsPerUnit, oHeight.Value / settings.PixelsPerUnit, 1);
                            obj.transform.localPosition = new Vector3((oX.Value - .5f * mapWidth * mapTileWidth + .5f * oWidth.Value) / settings.PixelsPerUnit,
                                                                      (-1 * (oY.Value - .5f * mapHeight * mapTileHeight + .5f * oHeight.Value)) / settings.PixelsPerUnit, 0);
                            if (oWidth.Value != oHeight.Value)
                            {
                                Debug.LogWarning("Unity does not support Ellispe, importing as Circle: " + obj.name);
                            }
                        }
                        else if (oElem.Element("polygon") != null && oX.HasValue && oY.HasValue)
                        {
                            PolygonCollider2D collider = obj.AddComponent <PolygonCollider2D>();
                            obj.transform.localPosition = new Vector3((oX.Value - .5f * mapWidth * mapTileWidth) / settings.PixelsPerUnit,
                                                                      (-1 * (oY.Value - .5f * mapHeight * mapTileHeight)) / settings.PixelsPerUnit, 0);

                            List <Vector2> points = new List <Vector2>();
                            foreach (var point in oElem.Element("polygon").Attribute("points").Value.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                            {
                                String[] coord = point.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                points.Add(new Vector2(Convert.ToSingle(coord[0]) / settings.PixelsPerUnit, (-1f * Convert.ToSingle(coord[1])) / settings.PixelsPerUnit));
                            }
                            collider.points = points.ToArray();
                        }
                        else if (oElem.Element("polyline") != null && oX.HasValue && oY.HasValue)
                        {
                            EdgeCollider2D collider = obj.AddComponent <EdgeCollider2D>();
                            obj.transform.localPosition = new Vector3((oX.Value - .5f * mapWidth * mapTileWidth) / settings.PixelsPerUnit,
                                                                      (-1 * (oY.Value - .5f * mapHeight * mapTileHeight)) / settings.PixelsPerUnit, 0);

                            List <Vector2> points = new List <Vector2>();
                            foreach (var point in oElem.Element("polyline").Attribute("points").Value.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                            {
                                String[] coord = point.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                points.Add(new Vector2(Convert.ToSingle(coord[0]) / settings.PixelsPerUnit, (-1 * Convert.ToSingle(coord[1])) / settings.PixelsPerUnit));
                            }
                            collider.points = points.ToArray();
                        }
                        else if (tileGID.HasValue)
                        {
                            SourceData sd     = gid2sprite[tileGID.Value];
                            Sprite     source = (Sprite)sprites.First(s => s.name.Equals(sd.spriteName));
                            obj.transform.localPosition = new Vector3((oX.Value - .5f * mapWidth * mapTileWidth + .5f * source.rect.width) / settings.PixelsPerUnit,
                                                                      (-1 * (oY.Value - .5f * mapHeight * mapTileHeight - .5f * source.rect.height)) / settings.PixelsPerUnit, 0);

                            SpriteRenderer sr = obj.AddComponent <SpriteRenderer>();

                            sr.sprite       = source;
                            sr.sortingOrder = sortOrder;
                            sr.color        = new Color(1, 1, 1, layerSettings.opacity);

                            BoxCollider2D collider = obj.AddComponent <BoxCollider2D>();
                            collider.size = new Vector2(source.rect.width / settings.PixelsPerUnit, source.rect.height / settings.PixelsPerUnit);

                            // LD29-specific
                            SetObjectType(obj, collider);
                            // ----------
                        }
                        else if (!tileGID.HasValue && oX.HasValue && oY.HasValue && oWidth.HasValue && oHeight.HasValue)
                        {
                            BoxCollider2D collider = obj.AddComponent <BoxCollider2D>();
                            obj.transform.localScale    = new Vector3(oWidth.Value / settings.PixelsPerUnit, oHeight.Value / settings.PixelsPerUnit, 1);
                            obj.transform.localPosition = new Vector3((oX.Value - .5f * mapWidth * mapTileWidth + .5f * oWidth.Value) / settings.PixelsPerUnit,
                                                                      (-1 * (oY.Value - .5f * mapHeight * mapTileHeight + .5f * oHeight.Value)) / settings.PixelsPerUnit, 0);

                            // LD29-specific
                            SetObjectType(obj, collider);
                            // ----------
                        }
                    }

                    olCount++;
                    sortOrder++;
                }
            }

            String     mapPrefapFile = mapDirectory + "/" + String.Format("{0}.prefab", mapName);
            GameObject mapPrefab     = PrefabUtility.CreatePrefab(mapPrefapFile, mapGameObject);

            EditorUtility.SetDirty(mapPrefab);
            GameObject.DestroyImmediate(mapGameObject);

            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
        }
 public bool acceptableEdge(EdgeCollider2D e, int n)
 {
     return(edge != e || edgePoint != n);
 }
示例#22
0
 void Start()
 {
     m_ptrEdgeCollider = GetComponent <EdgeCollider2D>();
     //   EventHandler.AddListener(EEventID.EVENT_LOAD_LEVEL, OnEventLoadLevel);
 }
        private void AddCollidersTo(GameObject gameObject, bool isTrigger, XElement xml)
        {
            // Box colliders
            foreach (XElement xmlBoxCollider2D in xml.Elements("BoxCollider2D"))
            {
                BoxCollider2D collider = gameObject.AddComponent <BoxCollider2D>();
                collider.isTrigger = isTrigger;
                float width  = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "width");
                float height = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "height");
                collider.size = new Vector2(width, height);
#if UNITY_5_0
                collider.offset = new Vector2(width * 0.5f, -height * 0.5f);
#else
                collider.center = new Vector2(width * 0.5f, -height * 0.5f);
#endif
            }

            // Circle colliders
            foreach (XElement xmlCircleCollider2D in xml.Elements("CircleCollider2D"))
            {
                CircleCollider2D collider = gameObject.AddComponent <CircleCollider2D>();
                collider.isTrigger = isTrigger;
                float radius = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "radius");
                collider.radius = radius;
#if UNITY_5_0
                collider.offset = new Vector2(radius, -radius);
#else
                collider.center = new Vector2(radius, -radius);
#endif
            }

            // Edge colliders
            foreach (XElement xmlEdgeCollider2D in xml.Elements("EdgeCollider2D"))
            {
                EdgeCollider2D collider = gameObject.AddComponent <EdgeCollider2D>();
                collider.isTrigger = isTrigger;
                string data = xmlEdgeCollider2D.Element("Points").Value;

                // The data looks like this:
                //  x0,y0 x1,y1 x2,y2 ...
                var points = from pt in data.Split(' ')
                             let x                 = Convert.ToSingle(pt.Split(',')[0])
                                             let y = Convert.ToSingle(pt.Split(',')[1])
                                                     select new Vector2(x, y);

                collider.points = points.ToArray();
            }

            // Polygon colliders
            foreach (XElement xmlPolygonCollider2D in xml.Elements("PolygonCollider2D"))
            {
                PolygonCollider2D collider = gameObject.AddComponent <PolygonCollider2D>();
                collider.isTrigger = isTrigger;

                var paths = xmlPolygonCollider2D.Elements("Path").ToArray();
                collider.pathCount = paths.Count();

                for (int p = 0; p < collider.pathCount; ++p)
                {
                    string data = paths[p].Value;

                    // The data looks like this:
                    //  x0,y0 x1,y1 x2,y2 ...
                    var points = from pt in data.Split(' ')
                                 let x                 = Convert.ToSingle(pt.Split(',')[0])
                                                 let y = Convert.ToSingle(pt.Split(',')[1])
                                                         select new Vector2(x, y);

                    collider.SetPath(p, points.ToArray());
                }
            }
        }
示例#24
0
 // Start is called before the first frame update
 void Start()
 {
     deadlyEdge = GetComponent <EdgeCollider2D>();
 }
示例#25
0
    public void checkObjModifiers(ObjectSave obj, GameObject curObj, string id)
    {
        if (obj.modifiers.ContainsKey("Background") && (obj.modifiers["Background"] == "true"))
        {
            curObj.GetComponent <Transform>().position += new Vector3(0.0f, 0.0f, GM.ZBackground);
        }

        // spawning object
        if (obj.modifiers.ContainsKey("spawner") && (obj.modifiers["spawner"] == "true"))
        {
            GM.Player     = new GameObject("Player");
            GM.Player.tag = "player";
            PlayerController PControl = GM.Player.AddComponent <PlayerController>();
            PControl.SetPosition(curObj.GetComponent <Transform>(), curObj.GetComponent <SpriteRenderer>());
            GM.Camera = GameObject.Find("Camera").GetComponent <CameraController>();
            GM.Camera.ReplaceCam(curObj, PControl);
        }
        // cam lock
        if (obj.modifiers.ContainsKey("camcollider") && (obj.modifiers["camcollider"] == "true"))
        {
            curObj.layer = LayerMask.NameToLayer("camera");
            curObj.tag   = "camlock";
            BoxCollider2D mybox = curObj.AddComponent <BoxCollider2D>();
            mybox.isTrigger = true;
        }
        // cam unlock
        if (obj.modifiers.ContainsKey("camcollider") && (obj.modifiers["camcollider"] == "false"))
        {
            curObj.layer = LayerMask.NameToLayer("camera");
            curObj.tag   = "camunlock";
            BoxCollider2D mybox = curObj.AddComponent <BoxCollider2D>();
            mybox.isTrigger = true;;
        }
        // collider ground
        if (obj.modifiers.ContainsKey("colliderground") && (obj.modifiers["colliderground"] == "true"))
        {
            curObj.layer = LayerMask.NameToLayer("ground");
            EdgeCollider2D mybox = curObj.AddComponent <EdgeCollider2D>();
            mybox.offset    = new Vector2(0, curObj.GetComponent <SpriteRenderer>().size.y / 2);
            mybox.isTrigger = false;
        }
        // collider
        if (obj.modifiers.ContainsKey("collider") && (obj.modifiers["collider"] == "true"))
        {
            curObj.layer = LayerMask.NameToLayer("collider");
            if (obj.modifiers.ContainsKey("face") && (obj.modifiers["face"] == "right"))
            {
                EdgeCollider2D mybox     = curObj.AddComponent <EdgeCollider2D>();
                Vector2[]      newPoints = new Vector2[2];
                newPoints[0] = new Vector2(0.0f, -2.5f);
                newPoints[1] = new Vector2(0.0f, 2.5f);
                mybox.points = newPoints;
                mybox.offset = new Vector2(curObj.GetComponent <SpriteRenderer>().size.x / 2, 0.0f);
            }
            else if (obj.modifiers.ContainsKey("face") && (obj.modifiers["face"] == "left"))
            {
                EdgeCollider2D mybox     = curObj.AddComponent <EdgeCollider2D>();
                Vector2[]      newPoints = new Vector2[2];
                newPoints[0] = new Vector2(0.0f, -2.5f);
                newPoints[1] = new Vector2(0.0f, 2.5f);
                mybox.points = newPoints;
                mybox.offset = new Vector2(-curObj.GetComponent <SpriteRenderer>().size.x / 2, 0.0f);
            }
            else
            {
                BoxCollider2D mybox = curObj.AddComponent <BoxCollider2D>();
                mybox.isTrigger = false;
            }
        }
        // level variables
        if ((id != "") && (string.Compare(id, "LevelVals") == 0))
        {
            PlayerPrefs.SetString("level", obj.modifiers["Name"]);
            GM.UI.setLevelName();
            PlayerPrefs.SetString("nextmap", obj.modifiers["NextLevel"]);
            GM.Player.AddComponent(Type.GetType(obj.modifiers["SpeScript"]));
            Destroy(curObj);
        }
        // invisible
        if (obj.modifiers.ContainsKey("visible") && (obj.modifiers["visible"] == "false"))
        {
            curObj.GetComponent <SpriteRenderer>().enabled = false;
        }
    }
 private void Awake()
 {
     edgeCollider2D     = GetComponent <EdgeCollider2D>();
     platformEffector2D = GetComponent <PlatformEffector2D>();
 }
        private void AddCollidersTo(GameObject gameObject, bool isTrigger, XElement xml)
        {
            // Box colliders
            foreach (XElement xmlBoxCollider2D in xml.Elements("BoxCollider2D"))
            {
                BoxCollider2D collider = gameObject.AddComponent <BoxCollider2D>();
                collider.isTrigger = isTrigger;
                float width  = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "width");
                float height = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "height");
                collider.size = new Vector2(width, height);

#if T2U_IS_UNITY_4
                collider.center = new Vector2(width * 0.5f, -height * 0.5f);
#else
                collider.offset = new Vector2(width * 0.5f, -height * 0.5f);
#endif
                // Apply the offsets (if any)
                float offset_x = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "offsetX", 0);
                float offset_y = ImportUtils.GetAttributeAsFloat(xmlBoxCollider2D, "offsetY", 0);

#if T2U_IS_UNITY_4
                collider.center += new Vector2(offset_x, offset_y);
#else
                collider.offset += new Vector2(offset_x, offset_y);
#endif
            }

            // Circle colliders
            foreach (XElement xmlCircleCollider2D in xml.Elements("CircleCollider2D"))
            {
                CircleCollider2D collider = gameObject.AddComponent <CircleCollider2D>();
                collider.isTrigger = isTrigger;
                float radius = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "radius");
                collider.radius = radius;
#if T2U_IS_UNITY_4
                collider.center = new Vector2(radius, -radius);
#else
                collider.offset = new Vector2(radius, -radius);
#endif

                // Apply the offsets (if any)
                float offset_x = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "offsetX", 0);
                float offset_y = ImportUtils.GetAttributeAsFloat(xmlCircleCollider2D, "offsetY", 0);

#if T2U_IS_UNITY_4
                collider.center += new Vector2(offset_x, offset_y);
#else
                collider.offset += new Vector2(offset_x, offset_y);
#endif
            }

            // Edge colliders
            foreach (XElement xmlEdgeCollider2D in xml.Elements("EdgeCollider2D"))
            {
                EdgeCollider2D collider = gameObject.AddComponent <EdgeCollider2D>();
                collider.isTrigger = isTrigger;
                string data = xmlEdgeCollider2D.Element("Points").Value;

                // The data looks like this:
                //  x0,y0 x1,y1 x2,y2 ...
                var points = from pt in data.Split(' ')
                             let x                 = Convert.ToSingle(pt.Split(',')[0])
                                             let y = Convert.ToSingle(pt.Split(',')[1])
                                                     select new Vector2(x, y);

                collider.points = points.ToArray();

                // Apply the offsets (if any)
                float offset_x = ImportUtils.GetAttributeAsFloat(xmlEdgeCollider2D, "offsetX", 0);
                float offset_y = ImportUtils.GetAttributeAsFloat(xmlEdgeCollider2D, "offsetY", 0);

#if T2U_IS_UNITY_4
                // This is kind of a hack for Unity 4.x which doesn't support offset/center on the edge collider
                var offsetPoints = from pt in points
                                   select new Vector2(pt.x + offset_x, pt.y + offset_y);
                collider.points = offsetPoints.ToArray();
#else
                collider.offset += new Vector2(offset_x, offset_y);
#endif
            }

            // Polygon colliders
            foreach (XElement xmlPolygonCollider2D in xml.Elements("PolygonCollider2D"))
            {
                PolygonCollider2D collider = gameObject.AddComponent <PolygonCollider2D>();
                collider.isTrigger = isTrigger;

                // Apply the offsets (if any)
                float offset_x = ImportUtils.GetAttributeAsFloat(xmlPolygonCollider2D, "offsetX", 0);
                float offset_y = ImportUtils.GetAttributeAsFloat(xmlPolygonCollider2D, "offsetY", 0);

                var paths = xmlPolygonCollider2D.Elements("Path").ToArray();
                collider.pathCount = paths.Count();

                for (int p = 0; p < collider.pathCount; ++p)
                {
                    string data = paths[p].Value;

                    // The data looks like this:
                    //  x0,y0 x1,y1 x2,y2 ...
                    var points = from pt in data.Split(' ')
                                 let x                 = Convert.ToSingle(pt.Split(',')[0])
                                                 let y = Convert.ToSingle(pt.Split(',')[1])
#if T2U_IS_UNITY_4
                                                         // Hack for Unity 4.x
                                                         select new Vector2(x + offset_x, y + offset_y);
#else
                                                         select new Vector2(x, y);
#endif

                    collider.SetPath(p, points.ToArray());
                }

#if !T2U_IS_UNITY_4
                collider.offset += new Vector2(offset_x, offset_y);
#endif
            }
        }
示例#28
0
    override protected void ShiftPoints()
    {
        EdgeCollider2D col = GetComponent <EdgeCollider2D>();

        col.points = GetShiftedPoints(col.points);
    }
示例#29
0
    public void BuildObject()
    {
        Logger.Info("Start building edge collider.");

        Transform ta = this.transform.FindChild("A");
        Transform tb = this.transform.FindChild("B");
        Transform tc = this.transform.FindChild("C");

        if (ta == null || tb == null || tc == null)
        {
            throw new MissingReferenceException();
        }

        Vector3 a = ta.position;
        Vector3 b = tb.position;
        Vector3 c = tc.position;

        float d = 2f * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));

        Vector3 u = new Vector3(
            ((a.x * a.x + a.y * a.y) * (b.y - c.y) + (b.x * b.x + b.y * b.y) * (c.y - a.y) + (c.x * c.x + c.y * c.y) * (a.y - b.y)) / d
            , ((a.x * a.x + a.y * a.y) * (c.x - b.x) + (b.x * b.x + b.y * b.y) * (a.x - c.x) + (c.x * c.x + c.y * c.y) * (b.x - a.x)) / d
            );

        GameObject arcObject = new GameObject();

        arcObject.name  = "Arc Edge Collider";
        arcObject.layer = LayerMask.NameToLayer("Platforms");

        EdgeCollider2D edgeCollider = arcObject.AddComponent <EdgeCollider2D>();

        List <Vector2> vectors = new List <Vector2>();

        float r = Vector3.Distance(a, u);

        Debug.Log("u: " + u + ", a: " + a + ", c: " + c);

        float sinb          = ((a.x - u.x) / r);
        float startAngleRad = Mathf.Asin(sinb);

        Debug.Log("Start angle: " + startAngleRad * Mathf.Rad2Deg);

        float sinb2       = ((c.x - u.x) / r);
        float endAngleRad = Mathf.Asin(sinb2);

        Debug.Log("End angle: " + endAngleRad * Mathf.Rad2Deg);

        if (startAngleRad > endAngleRad)
        {
            float temp = startAngleRad;
            startAngleRad = endAngleRad;
            endAngleRad   = temp;
        }

        Vector3 startPoint      = u + new Vector3((float)(r * Mathf.Cos(endAngleRad)), (float)(r * Mathf.Sin(endAngleRad)));
        float   sinb3           = ((startPoint.x - u.x) / r);
        float   startPointAngle = Mathf.Asin(sinb3);

        float rotAngle = startAngleRad - startPointAngle;

        startAngleRad -= rotAngle;
        endAngleRad   -= rotAngle;

        float totalAngle = Mathf.Abs(startAngleRad - endAngleRad);

        float max  = totalAngle;// 2.0f * Mathf.PI;
        float step = max / (totalSegments);

        Debug.Log(startAngleRad * Mathf.Rad2Deg);
        Debug.Log(endAngleRad * Mathf.Rad2Deg);
        Debug.Log(r);

        float bottomPosition = float.MaxValue;

        for (float theta = endAngleRad; theta > startAngleRad - step / 2; theta -= step)
        {
            Vector2 vector = new Vector2((float)(r * Mathf.Cos(theta)), (float)(r * Mathf.Sin(theta)));
            vectors.Add(vector);
            if (vector.y < bottomPosition)
            {
                bottomPosition = vector.y;
            }
        }
        for (int i = 0; i < vectors.Count; i++)
        {
            vectors[i] = new Vector2(vectors[i].x, vectors[i].y - bottomPosition);
        }

        arcObject.transform.position = new Vector2(u.x, u.y + bottomPosition);

        edgeCollider.points = vectors.ToArray();

        arcObject.transform.parent = this.transform;

        if (meshBuilderFillType != MeshBuilderFillType.NoFill)
        {
            CreateMesh(arcObject, edgeCollider);
        }
    }
    void Update()
    {
        if (Input.GetMouseButtonUp(0) && doing == false)
        {
            // Bool parameter
            doing = true;

            // Creation of GO
            GameObject newGo = new GameObject("newColl" + Time.time);
            newGo.tag = "Respawn";
            Vector3 location = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            location.z = 0;

            // Set as mouse position
            newGo.transform.position = location;


            if (Input.GetKey(KeyCode.A))
            {
                //Create the BoxCollider2D
                //----------------------------

                BoxCollider2D polyCol = newGo.AddComponent <BoxCollider2D>();
                polyCol.offset = Vector2.zero;
                polyCol.size   = new Vector2(1, 1);

                // important Step: adding to current 2ddl layer
                polyCol.gameObject.layer = LayerMask.NameToLayer("Default");
                //Push collider to the main array or vertices
                light2d.addColliderToScene(polyCol);
            }
            else if (Input.GetKey(KeyCode.B))
            {
                //Create the BoxCollider2D
                //----------------------------

                CircleCollider2D polyCol = newGo.AddComponent <CircleCollider2D>();

                polyCol.offset = Vector2.zero;
                polyCol.radius = 2f;

                // important Step: adding to current 2ddl layer
                polyCol.gameObject.layer = LayerMask.NameToLayer("Default");

                //Push collider to the main array or vertices
                light2d.addColliderToScene(polyCol);
            }
            else if (Input.GetKey(KeyCode.C))
            {
                //Create the BoxCollider2D
                //----------------------------

                EdgeCollider2D polyCol = newGo.AddComponent <EdgeCollider2D>();

                Vector2[] ColPoints = new Vector2[3];
                ColPoints[0]   = new Vector2(0, -1);
                ColPoints[1]   = new Vector2(1, -1);
                ColPoints[2]   = new Vector2(1, -1.5f);
                polyCol.points = ColPoints;

                // important Step: adding to current 2ddl layer
                polyCol.gameObject.layer = LayerMask.NameToLayer("Default");

                //Push collider to the main array or vertices
                light2d.addColliderToScene(polyCol);
            }
            else
            {
                //Create the polygonCollider2D
                //----------------------------

                PolygonCollider2D polyCol   = newGo.AddComponent <PolygonCollider2D>();
                Vector2[]         ColPoints = new Vector2[5];
                ColPoints[0] = new Vector2(-1, -1);
                ColPoints[1] = new Vector2(1, -1);
                ColPoints[2] = new Vector2(1, 1);
                ColPoints[3] = new Vector2(-.5f, 1.5f);
                ColPoints[4] = new Vector2(-1, 1);

                polyCol.points = ColPoints;

                // important Step: adding to current 2ddl layer
                polyCol.gameObject.layer = LayerMask.NameToLayer("Default");
                //Push collider to the main array or vertices
                light2d.addColliderToScene(polyCol);
            }



            //Restoring privileges for creation
            StartCoroutine(restoreDoing());
        }
    }