示例#1
0
        public TmxMap(XElement mapElement)
        {
            foreach (var attribute in mapElement.Attributes())
            {
                switch (attribute.Name.LocalName.ToLower())
                {
                case "version":
                    Version = attribute.Value;
                    break;

                case "orientation":
                    Orientation = (MapOrientation)Enum.Parse(typeof(MapOrientation), attribute.Value, true);
                    break;

                case "width":
                    Width = int.Parse(attribute.Value);
                    break;

                case "height":
                    Height = int.Parse(attribute.Value);
                    break;

                case "tilewidth":
                    TileWidth = int.Parse(attribute.Value);
                    break;

                case "tileheight":
                    TileHeight = int.Parse(attribute.Value);
                    break;

                case "backgroundcolor":
                    string hex = attribute.Value.TrimStart('#');
                    BackgroundColor = new Color(Convert.ToByte(hex.Substring(0, 2), 16),
                                                Convert.ToByte(hex.Substring(2, 2), 16),
                                                Convert.ToByte(hex.Substring(4, 2), 16));
                    break;
                }
            }
            foreach (var subElement in mapElement.Elements())
            {
                switch (subElement.Name.LocalName.ToLower())
                {
                case "tileset":
                    var ts = new TmxTileset(subElement);
                    Tilesets.Add(ts.Name, ts);
                    break;

                case "layer":
                    var l = new TmxLayer(subElement);
                    Layers.Add(l.Name, l);
                    break;
                }
            }
        }
示例#2
0
 public Map(string name, int width, int height, int tileWidth, int tileHeight, MapOrientation orientation = MapOrientation.Isometric)
     : base(name)
 {
     backgroundColor  = new Color(0, 0, 0, 255);
     this.width       = width;
     this.height      = height;
     this.tileWidth   = tileWidth;
     this.tileHeight  = tileHeight;
     startX           = -1;
     startY           = -1;
     layers           = new List <Layer>();
     this.orientation = orientation;
     eventLayer       = new EventLayer(width, height);
     loadEvents       = new List <Event>();
     loadNPCs         = new List <EntityLoadInfo>();
     loadEnemyGroups  = new List <EnemyGroup>();
 }
示例#3
0
文件: Camera.cs 项目: Jebeli/Tiles
 public Camera(Engine engine, Map map, int posX = -1, int posY = -1)
 {
     this.engine     = engine;
     this.map        = map;
     cameraSpeed     = 10.0f;
     immediateCamera = false;
     selectedTileX   = -1;
     selectedTileY   = -1;
     orientation     = map.Orientation;
     tileWidth       = map.TileWidth;
     tileHeight      = map.TileHeight;
     halfTileWidth   = tileWidth / 2;
     halfTileHeight  = tileHeight / 2;
     if (orientation == MapOrientation.Isometric)
     {
         unitsPerPixelX = 2.0f / tileWidth;
         unitsPerPixelY = 2.0f / tileHeight;
     }
     else
     {
         unitsPerPixelX = 1.0f / tileWidth;
         unitsPerPixelY = 1.0f / tileHeight;
     }
     viewWidth      = engine.Graphics.ViewWidth;
     halfViewWidth  = viewWidth / 2;
     viewHeight     = engine.Graphics.ViewHeight;
     halfViewHeight = viewHeight / 2;
     if (posX >= 0 && posY >= 0)
     {
         SetPosition(posX, posY);
     }
     else if (map.StartX >= 0 && map.StartY >= 0)
     {
         SetPosition(map.StartX, map.StartY);
     }
     else
     {
         SetPosition(map.Width / 2.0f, map.Height / 2.0f);
     }
 }
示例#4
0
        private void DrawTile(int x, int y, int width, int height, Color color, MapOrientation orientation = MapOrientation.Isometric)
        {
            if (orientation == MapOrientation.Orthogonal)
            {
                SDL.SDL_Rect rect = new SDL.SDL_Rect();
                rect.x = x;
                rect.y = y;
                rect.w = width;
                rect.h = height;
                SDL.SDL_SetRenderDrawBlendMode(game.ren, SDL.SDL_BlendMode.SDL_BLENDMODE_BLEND);
                SDL.SDL_SetRenderDrawColor(game.ren, color.R, color.G, color.B, color.Alpha);
                SDL.SDL_RenderDrawRect(game.ren, ref rect);
            }
            else
            {
                SDL.SDL_SetRenderDrawBlendMode(game.ren, SDL.SDL_BlendMode.SDL_BLENDMODE_BLEND);
                SDL.SDL_SetRenderDrawColor(game.ren, color.R, color.G, color.B, color.Alpha);
                int leftX   = x;
                int leftY   = y;
                int topX    = x + width / 2;
                int topY    = y - height / 2;
                int rightX  = x + width;
                int rightY  = y;
                int bottomX = x + width / 2;
                int bottomY = y + height / 2;

                //int x1 = x;
                //int x2 = x + width / 2;
                //int x3 = x + width;
                //int y1 = y;
                //int y2 = y + height / 2;
                //int y3 = y + height;
                SDL.SDL_RenderDrawLine(game.ren, leftX, leftY, topX, topY);
                SDL.SDL_RenderDrawLine(game.ren, topX, topY, rightX, rightY);
                SDL.SDL_RenderDrawLine(game.ren, rightX, rightY, bottomX, bottomY);
                SDL.SDL_RenderDrawLine(game.ren, bottomX, bottomY, leftX, leftY);
            }
        }
示例#5
0
        // This must be called in order for rotation and position offset to by applied
        public void RenderPoints(SuperTile tile, MapOrientation orientation, Vector2 gridSize)
        {
            if (orientation == MapOrientation.Isometric)
            {
                m_Position    = IsometricTransform(m_Position, tile, gridSize);
                m_Position.x += gridSize.x * 0.5f;
                m_Position.y += tile.m_Height - gridSize.y;

                for (int i = 0; i < m_Points.Length; i++)
                {
                    m_Points[i] = IsometricTransform(m_Points[i], tile, gridSize);
                }

                // Also, we are forced to use polygon colliders for isometric projection
                if (m_CollisionShapeType == CollisionShapeType.Ellipse || m_CollisionShapeType == CollisionShapeType.Rectangle)
                {
                    m_CollisionShapeType = CollisionShapeType.Polygon;
                }
            }

            ApplyRotationToPoints();
            m_Points = m_Points.Select(p => p + m_Position).ToArray();
        }
示例#6
0
		public ExtendedMap(MapSpan span) : base(span)
		{
			mapOrientation = MapOrientation.NorthUp;
		}
示例#7
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");

                    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

                    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);
                        }
                        else if (!tileGID.HasValue && oX.HasValue && oY.HasValue && oWidth.HasValue && oHeight.HasValue)
                        {
                            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);
                        }
                    }

                    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);
        }
示例#8
0
 public override void DrawTileSelected(int x, int y, int width, int height, MapOrientation oriention = MapOrientation.Isometric)
 {
     x += transX;
     y += transY;
     DrawTile(x, y, width, height, Microsoft.Xna.Framework.Color.Gold * 0.48f, oriention);
 }
示例#9
0
 private void DrawTile(int x, int y, int width, int height, Microsoft.Xna.Framework.Color color, MapOrientation oriention = MapOrientation.Isometric)
 {
     x += transX;
     y += transY;
     if (oriention == MapOrientation.Orthogonal)
     {
         var rect = new Microsoft.Xna.Framework.Rectangle(x, y, width, height);
         batch.DrawRectangle(rect, color);
     }
     else
     {
         float x1 = x;
         float x2 = x + width / 2;
         float x3 = x + width;
         float y1 = y;
         float y2 = y + height / 2;
         float y3 = y + height;
         batch.DrawLine(new Microsoft.Xna.Framework.Vector2(x1, y2), new Microsoft.Xna.Framework.Vector2(x2, y1), color);
         batch.DrawLine(new Microsoft.Xna.Framework.Vector2(x2, y1), new Microsoft.Xna.Framework.Vector2(x3, y2), color);
         batch.DrawLine(new Microsoft.Xna.Framework.Vector2(x3, y2), new Microsoft.Xna.Framework.Vector2(x2, y3), color);
         batch.DrawLine(new Microsoft.Xna.Framework.Vector2(x2, y3), new Microsoft.Xna.Framework.Vector2(x1, y2), color);
     }
 }
示例#10
0
文件: Camera.cs 项目: Jebeli/Tiles
 public void MapToScreen(float mapX, float mapY, out int screenX, out int screenY, MapOrientation orientation)
 {
     MapToScreen(mapX, mapY, shakyCamX, shakyCamY, out screenX, out screenY, orientation);
 }
示例#11
0
    public static Map ImportMap(string mapFilename)
    {
        XDocument input = XDocument.Load(mapFilename);

        MapOrientation mapOrientation = MapOrientation.Unsupported;

        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;

        case "hexagonal":
            mapOrientation = MapOrientation.Hexagonal;
            break;

        default:
            mapOrientation = MapOrientation.Unsupported;
            break;
        }

        if (mapOrientation == MapOrientation.Unsupported)
        {
            throw new NotSupportedException("Map - Unsupported map type: " + input.Document.Root.Attribute("orientation").Value);
        }

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

        MapRenderOrder mapRenderOrder = MapRenderOrder.LeftDown;

        if (input.Document.Root.Attribute("renderorder") != null)
        {
            switch (input.Document.Root.Attribute("renderorder").Value)
            {
            case "right-down":
                mapRenderOrder = MapRenderOrder.RightDown;
                break;

            case "right-up":
                mapRenderOrder = MapRenderOrder.RightUp;
                break;

            case "left-down":
                mapRenderOrder = MapRenderOrder.LeftDown;
                break;

            case "left-up":
                mapRenderOrder = MapRenderOrder.LeftUp;
                break;

            default:
                mapRenderOrder = MapRenderOrder.Unsupported;
                break;
            }

            if (mapRenderOrder == MapRenderOrder.Unsupported)
            {
                throw new NotSupportedException("UTiled - Unsupported map render order: " + input.Document.Root.Attribute("renderorder").Value);
            }
        }

        Debug.Log("Map Name: " + mapName);
        Debug.Log("   " + mapWidth + "x" + mapHeight + " (" + mapTileWidth + "x" + mapTileHeight + ")");
        Debug.Log("   RenderOrder: " + mapRenderOrder.ToString());

        Dictionary <UInt32, Tile> gidToSprite = new Dictionary <UInt32, Tile>();

        Int32 tsNum = 1;

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

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

            /*
             * 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);
            }

            foreach (var tile in elem.Elements("tile"))
            {
                UInt32 gid   = Convert.ToUInt32(tile.Attribute("id").Value);
                var    image = tile.Element("image");
                if (image == null)
                {
                    continue;
                }

                string exits = null;

                /*
                 * Debug.LogError("Properties: " + tile.Elements("properties"));
                 * foreach (var property in tile.Elements("properties")) {
                 * }
                 */
                XElement properties = tile.Element("properties");

                /*
                 * if (properties != null) {
                 *
                 *      foreach (var property in properties.Elements ("property")) {
                 *              Debug.LogError("Attribute: " + property.Name);
                 *              if (property.Attribute ("name") != null && property.Attribute("name").Value == "exits") {
                 *                      exits = property.Attribute("value").Value;
                 *                      break;
                 *              }
                 *      }
                 * }
                 */

                float  imageWidth  = Convert.ToSingle(image.Attribute("width").Value);
                float  imageHeight = Convert.ToSingle(image.Attribute("height").Value);
                string sourceFile  = image.Attribute("source").Value;
                Tile   tileObject  = new Tile(sourceFile, properties);

                gidToSprite[gid + FirstGID] = tileObject;
            }
        }

        List <UInt32> gids = null;

        foreach (var lElem in input.Document.Root.Elements())
        {
            if (lElem.Name.LocalName.Equals("layer"))
            {
                gids = parseLayer(lElem);
            }
        }

        if (gids == null)
        {
            return(null);
        }

        return(new Map((int)mapWidth, (int)mapHeight, gidToSprite, gids));
    }
        public TilePolygonCollection(SuperTile tile, TileIdMath tileId, SuperImportContext importContext, MapOrientation orientation)
        {
            m_ImportContext = importContext;

            m_Tile   = tile;
            m_TileId = tileId;

            m_Transform = m_Tile.GetTransformMatrix(m_TileId.FlipFlags, orientation);

            CollectTilePolygons();
        }
示例#13
0
 private void DrawTile(int x, int y, int width, int height, System.Drawing.Pen pen, MapOrientation oriention = MapOrientation.Isometric)
 {
     if (oriention == MapOrientation.Orthogonal)
     {
         var rect = new System.Drawing.Rectangle(x, y, width, height);
         gfx.DrawRectangle(pen, rect);
     }
     else
     {
         float x1 = x;
         float x2 = x + width / 2;
         float x3 = x + width;
         float y1 = y;
         float y2 = y + height / 2;
         float y3 = y + height;
         System.Drawing.PointF[] poly = new System.Drawing.PointF[5];
         poly[0].X = x1;
         poly[0].Y = y2;
         poly[1].X = x2;
         poly[1].Y = y1;
         poly[2].X = x3;
         poly[2].Y = y2;
         poly[3].X = x2;
         poly[3].Y = y3;
         poly[4].X = x1;
         poly[4].Y = y2;
         gfx.DrawPolygon(pen, poly);
     }
 }
示例#14
0
        public void GetTRS(FlipFlags flags, MapOrientation orientation, out Vector3 xfTranslate, out Vector3 xfRotate, out Vector3 xfScale)
        {
            float inversePPU = 1.0f / m_Sprite.pixelsPerUnit;
            float width      = m_Width * inversePPU;
            float height     = m_Height * inversePPU;

            bool flippedHorizontally   = FlipFlagsMask.FlippedHorizontally(flags);
            bool flippedVertically     = FlipFlagsMask.FlippedVertically(flags);
            bool rotatedDiagonally     = FlipFlagsMask.RotatedDiagonally(flags);
            bool rotatedHexagonally120 = FlipFlagsMask.RotatedHexagonally120(flags);

            xfTranslate = Vector3.zero;
            xfRotate    = Vector3.zero;
            xfScale     = Vector3.one;

            if (flags != FlipFlags.None)
            {
                if (orientation == MapOrientation.Hexagonal)
                {
                    if (rotatedDiagonally)
                    {
                        xfRotate.z -= 60;
                    }

                    if (rotatedHexagonally120)
                    {
                        xfRotate.z -= 120;
                    }
                }
                else if (rotatedDiagonally)
                {
                    xfRotate.z = -90.0f;

                    flippedHorizontally = FlipFlagsMask.FlippedVertically(flags);
                    flippedVertically   = !FlipFlagsMask.FlippedHorizontally(flags);
                }

                xfScale.x = flippedHorizontally ? -1.0f : 1.0f;
                xfScale.y = flippedVertically ? -1.0f : 1.0f;

                var matScale  = Matrix4x4.Scale(xfScale);
                var matRotate = Matrix4x4.Rotate(Quaternion.Euler(xfRotate));

                if (orientation == MapOrientation.Hexagonal)
                {
                    // Hex tiles use the center of the tile for transforms
                    var anchor = new Vector3(width * 0.5f, height * 0.5f);

                    var transformed = matScale.MultiplyPoint(anchor);
                    transformed = matRotate.MultiplyPoint(transformed);

                    xfTranslate.x = anchor.x - transformed.x;
                    xfTranslate.y = anchor.y - transformed.y;
                }
                else
                {
                    // Mulitply the corners for our tile against rotation and scale matrices to see what our translation should be to get the tile back to the bottom-left origin
                    var points = new Vector3[]
                    {
                        new Vector3(0, height, 0),
                        new Vector3(width, height, 0),
                        new Vector3(width, 0, 0),
                    };

                    points = points.Select(p => matScale.MultiplyPoint(p)).ToArray();
                    points = points.Select(p => matRotate.MultiplyPoint(p)).ToArray();

                    var minX = points.Select(p => p.x).Min();
                    var minY = points.Select(p => p.y).Min();

                    xfTranslate.x = -minX;
                    xfTranslate.y = -minY;
                }
            }

            // Each tile may have an additional offset
            xfTranslate.x += m_TileOffsetX * inversePPU;
            xfTranslate.y -= m_TileOffsetY * inversePPU;
        }
示例#15
0
 public override void DrawTileGrid(int x, int y, int width, int height, MapOrientation oriention = MapOrientation.Isometric)
 {
     x += transX;
     y += transY;
     DrawTile(x, y, width, height, new Color(245, 222, 179, 128), oriention);
 }
示例#16
0
        public Matrix4x4 GetTransformMatrix(FlipFlags ff, MapOrientation orientation)
        {
            var inversePPU = 1.0f / m_Sprite.pixelsPerUnit;
            var offset     = new Vector2(m_TileOffsetX * inversePPU, -m_TileOffsetY * inversePPU);
            var matOffset  = Matrix4x4.Translate(offset);

            if (ff == FlipFlags.None)
            {
                return(matOffset);
            }

            bool flipHorizontal = FlipFlagsMask.FlippedHorizontally(ff);
            bool flipVertical   = FlipFlagsMask.FlippedVertically(ff);
            bool flipDiagonal   = FlipFlagsMask.RotatedDiagonally(ff);
            bool rotateHex120   = FlipFlagsMask.RotatedHexagonally120(ff);

            float width  = m_Width * inversePPU;
            float height = m_Height * inversePPU;

            var tileCenter = new Vector2(width, height) * 0.5f;

            Matrix4x4 matTransIn  = Matrix4x4.identity;
            Matrix4x4 matFlip     = Matrix4x4.identity;
            Matrix4x4 matTransOut = Matrix4x4.identity;

            // Go to the tile center
            matTransIn = Matrix4x4.Translate(-tileCenter);

            if (orientation == MapOrientation.Hexagonal)
            {
                if (flipDiagonal)
                {
                    matFlip *= Rotate60Matrix;
                }

                if (rotateHex120)
                {
                    matFlip *= Rotate120Matrix;
                }

                if (flipHorizontal)
                {
                    matFlip *= HorizontalFlipMatrix;
                }

                if (flipVertical)
                {
                    matFlip *= VerticalFlipMatrix;
                }

                matTransOut = Matrix4x4.Translate(tileCenter);
            }
            else
            {
                if (flipHorizontal)
                {
                    matFlip *= HorizontalFlipMatrix;
                }

                if (flipVertical)
                {
                    matFlip *= VerticalFlipMatrix;
                }

                if (flipDiagonal)
                {
                    matFlip *= DiagonalFlipMatrix;
                }

                // Go out of the tile center
                if (!flipDiagonal)
                {
                    matTransOut = Matrix4x4.Translate(tileCenter);
                }
                else
                {
                    // Compensate for width and height being different dimensions
                    float diff = (height - width) * 0.5f;
                    tileCenter.x += diff;
                    tileCenter.y -= diff;
                    matTransOut   = Matrix4x4.Translate(tileCenter);
                }
            }

            // Put it all together
            return(matOffset * matTransOut * matFlip * matTransIn);
        }
示例#17
0
文件: Camera.cs 项目: Jebeli/Tiles
 public void ScreenToMap(float screenX, float screenY, float camX, float camY, out float mapX, out float mapY, MapOrientation orientation)
 {
     if (orientation == MapOrientation.Isometric)
     {
         IsoScreenToMap(screenX, screenY, camX, camY, out mapX, out mapY);
     }
     else
     {
         OrthoScreenToMap(screenX, screenY, camX, camY, out mapX, out mapY);
     }
 }
示例#18
0
文件: Camera.cs 项目: Jebeli/Tiles
 public void ScreenToMap(float screenX, float screenY, out float mapX, out float mapY, MapOrientation orientation)
 {
     ScreenToMap(screenX, screenY, shakyCamX, shakyCamY, out mapX, out mapY, orientation);
 }
示例#19
0
文件: TmxMap.cs 项目: ruttlej/CS7038
 public TmxMap()
 {
     Layers      = new List <Layer>();
     Objects     = new List <TmxObject>();
     Orientation = MapOrientation.Orthogonal;
 }
示例#20
0
        public static Vector3 ToVector3(float width, float height, float inversePPU, MapOrientation mapOrientation, ObjectAlignment objectAlignment)
        {
            width  *= inversePPU;
            height *= inversePPU;

            float dx = 0;
            float dy = 0;

            if (objectAlignment == ObjectAlignment.Unspecified)
            {
                objectAlignment = mapOrientation == MapOrientation.Isometric ? ObjectAlignment.Bottom : ObjectAlignment.BottomLeft;
            }

            switch (objectAlignment)
            {
            case ObjectAlignment.BottomLeft:
                dx = 0;
                dy = 0;
                break;

            case ObjectAlignment.Top:
                dx = -width * 0.5f;
                dy = -height;
                break;

            case ObjectAlignment.TopRight:
                dx = -width;
                dy = -height;
                break;

            case ObjectAlignment.TopLeft:
                dx = 0;
                dy = -height;
                break;

            case ObjectAlignment.Left:
                dx = 0;
                dy = -height * 0.5f;
                break;

            case ObjectAlignment.Center:
                dx = -width * 0.5f;
                dy = -height * 0.5f;
                break;

            case ObjectAlignment.Right:
                dx = -width;
                dy = -height * 0.5f;
                break;

            case ObjectAlignment.Bottom:
                dx = -width * 0.5f;
                dy = 0;
                break;

            case ObjectAlignment.BottomRight:
                dx = -width;
                dy = 0;
                break;
            }

            return(new Vector3(dx, dy, 0));
        }
示例#21
0
 public override void DrawTileSelected(int x, int y, int width, int height, MapOrientation oriention = MapOrientation.Isometric)
 {
     x += transX;
     y += transY;
     DrawTile(x, y, width, height, selectPen, oriention);
 }
示例#22
0
 public abstract void DrawTileSelected(int x, int y, int width, int height, MapOrientation oriention = MapOrientation.Isometric);
示例#23
0
 public override void DrawTileSelected(int x, int y, int width, int height, MapOrientation oriention = MapOrientation.Isometric)
 {
     x += transX;
     y += transY;
     DrawTile(x, y, width, height, new Color(255, 215, 0, 128), oriention);
 }
示例#24
0
文件: Camera.cs 项目: Jebeli/Tiles
 public void MapToScreen(float mapX, float mapY, float camX, float camY, out int screenX, out int screenY, MapOrientation orientation)
 {
     if (orientation == MapOrientation.Isometric)
     {
         IsoMapToScreen(mapX, mapY, camX, camY, out screenX, out screenY);
     }
     else
     {
         OrthoMapToScreen(mapX, mapY, camX, camY, out screenX, out screenY);
     }
 }
示例#25
0
        private TilePolygonCollection AcquireTilePolygonCollection(SuperTile tile, TileIdMath tileId, MapOrientation orientation)
        {
            TilePolygonCollection polygons;

            if (m_TilePolygonDatabase.TryGetValue(tileId.ImportedlTileId, out polygons))
            {
                return(polygons);
            }

            // If we're here then we don't have a polygon collection for this tile yet
            polygons = new TilePolygonCollection(tile, tileId, m_ImportContext, orientation);
            m_TilePolygonDatabase.Add(tileId.ImportedlTileId, polygons);
            return(polygons);
        }
示例#26
0
        void DrawGrid(float size_x, float size_y, int count_x, int count_y, Vector3 pos, Quaternion rot, MapOrientation type, Color c)
        {
            float h = count_y * size_y;
            float w = count_x * size_x;

            Gizmos.color = c;

            Vector3 trans;

            if (oriantion == MapOrientation.xSwaped)
            {
                trans = new Vector3(-1, 1, 1);
            }
            else if (oriantion == MapOrientation.ySwaped)
            {
                trans = new Vector3(1, -1, 1);
            }
            else if (oriantion == MapOrientation.xySwaped)
            {
                trans = new Vector3(-1, -1, 1);
            }
            else
            {
                trans = new Vector3(1, 1, 1);
            }

            for (int i = 0; i < count_x + 1; i++)
            {
                float x = (i * size_x);

                Vector3 start = rot * Vector3.Scale(
                    new Vector3(
                        x,
                        0,
                        0
                        ), trans);
                Vector3 end = rot * Vector3.Scale(
                    new Vector3(
                        x,
                        h,
                        0
                        ), trans);
                Gizmos.DrawLine(start + pos, end + pos);
            }

            for (int i = 0; i < count_y + 1; i++)
            {
                float y = (i * size_y);

                Vector3 start = rot * Vector3.Scale(
                    new Vector3(
                        0,
                        y,
                        0
                        ), trans);
                Vector3 end = rot * Vector3.Scale(
                    new Vector3(
                        w,
                        y,
                        0
                        ), trans);
                Gizmos.DrawLine(start + pos, end + pos);
            }

            Gizmos.color = Color.white;
        }