Esempio n. 1
0
 // Use this for initialization
 void Start()
 {
     turnManager = GameObject.Find("AITurnManager").GetComponent<AITurnManager>();
     unit = transform.parent.GetComponent<TileObject>();
     movePoints = transform.FindChild("MovePoints").GetComponent<Text>();
     healthBar = transform.FindChild("Health").FindChild("HealthGreen").GetComponent<Image>();
     sanityBar = transform.FindChild("Sanity").FindChild("SanityBlue").GetComponent<Image>();
 }
Esempio n. 2
0
    /**
     * return a list of tiles that touch this tile
     **/
    public ArrayList FindNearbyTiles(TileObject tile)
    {
        ArrayList alist = new ArrayList();
        foreach(Transform child in tiles.transform){
            if(tile.IsInsideFlameRadius(child.position))
                alist.Add(child.gameObject);
        }

        return alist;
    }
Esempio n. 3
0
 //constructor
 public MainForm()
 {
     InitializeComponent();
     _MapObj = new MapObject();
     _QuadTree = null;
     InitListPb();
     _IsMouseDown = false;
     _SelectedObj = null;
     _startPoint = new Point();
     _endPoint = new Point();
 }
Esempio n. 4
0
 public void Populate(TileObject citizen)
 {
     tiles.Add(citizen, new List<Vector2>());
     for (int x = 0; x < width; x++)
     {
         for (int y = 0; y < height; y++)
         {
             tiles[citizen].Add(new Vector2(x, y));
         }
     }
     Populate();
 }
Esempio n. 5
0
    public bool CanMoveInDirection(TileObject to, Vector2 dir)
    {
        int x = to.x + (int)dir.x;
        int y = to.y + (int)dir.y;

        float dumbtimer = 0;
        int moves = 0;
        while (true && dumbtimer < 4){
            dumbtimer += Time.deltaTime;
            //			Debug.Log("dumbtimer: " + dumbtimer + ", x: " + x + " ,y: "+ y);
            if (!IsPositionValid(x, y)) return false;

            switch (map[x,y].type) {
            case TileType.BOX:
                x += (int)dir.x;
                y += (int)dir.y;
                break;
            case TileType.WALL:
                return false;
            case TileType.EMPTY:
                return true;
            case TileType.EXIT:
                if (moves == 0 && to.type == TileType.PLAYER) return true;
                return false;
            case TileType.DOOR:
                Debug.Log("map[x,y].keyType: " + map[x,y].keyType + ", to.keyType: " + to.keyType);
                if (moves == 0 && to.type == TileType.KEY && map[x,y].keyType == to.keyType) return true;
                return false;
            case TileType.KEY:
                x += (int)dir.x;
                y += (int)dir.y;
                break;
            case TileType.LASER:
                x += (int)dir.x;
                y += (int)dir.y;
                break;
            case TileType.WATER:
                if (moves == 0 && to.type == TileType.BOX) return true;  //TODO handle box in water
                return false;
            case TileType.PLAYER:
                x += (int)dir.x;
                y += (int)dir.y;
                break;
            default:
                break;
            }
            moves++;
        }
        return false;
    }
Esempio n. 6
0
    // Public Method
    #region Public Method

    /// <summary>
    /// ObjectTile를 생성시 작업
    /// Isntantiate를 통해서 자신의 객층구조상 위치(부모의 Transform)에 객체를 생성하며,
    /// 생성시 Renderer를 끄고, 필요한 기본정보를 작성 해줌
    /// </summary>
    /// <param name="_GameObject">만들 객체</param>
    /// <param name="_StandardPos">타일의 0,0값</param>
    /// <param name="_row">행</param>
    /// <param name="_Cloum">렬</param>
    /// <param name="_ParentTransform">부모의 Transform</param>
    override public void Instantiate(GameObject _GameObject, Vector3 _StandardPos, int _row, int _Cloum, Transform _ParentTransform)
    {
        GameObject f_Object = Instantiate <GameObject>(_GameObject, new Vector3(_StandardPos.x + (0.16f * _row), _StandardPos.y + (0.16f * _Cloum), 0), Quaternion.identity, _ParentTransform);

        TileObject f_TileObject = f_Object.GetComponent <TileObject>();

        f_TileObject.Renderer.enabled = false;

        if (f_TileObject != null)
        {
            f_TileObject.Initialized(_row, _Cloum);
            SetObjectPoket(f_TileObject, _row, _Cloum);
        }

        SpawnObjects.Add(f_Object);
    }
Esempio n. 7
0
        public void Destroy(TileObject tileObject)
        {
            NetworkManager.Instance.DestroyTileObject(tileObject);
            UnregisterPosition(tileObject);
            UnregisterUpdateable(tileObject);
            tileObject.OnDestroy();
            tileObject.SetScene(null);

            if (tileObject.GetInstanceId() == -1)
            {
                LogManager.RuntimeLogger.LogError($"[Scene] {tileObject.VisibleName} is not instantiated");
            }

            _instantiatedTileObjects[tileObject.GetInstanceId()] = null;
            tileObject.SetInstanceId(-1);
        }
Esempio n. 8
0
    void Start()
    {
        var sprites = ResourceManager.Instance.GetSpriteMap();

        foreach (var item in sprites)
        {
            GameObject go  = new GameObject();
            var        img = go.AddComponent <Image>();
            img.sprite = item.Value;
            go.transform.SetParent(_scrollContainer.transform);

            var        contentItem = go.AddComponent <ContentItem>();
            TileObject tileObject  = new TileObject(ResourceManager.Instance.GetTilePrefab(item.Key), 500);
            contentItem.tileObject = tileObject;
        }
    }
Esempio n. 9
0
        IDragable FindDragable()
        {
            UiElement ui     = _pointerDataProvider.UnderCursorUiElement;
            IDragable result = ui as IDragable;

            if (result != null)
            {
                return(result);
            }

            TileObject to = _pointerDataProvider.UnderCursorTileObject;

            result = to as IDragable;

            return(result);
        }
Esempio n. 10
0
        IDropReceiver FindDropReceiver()
        {
            UiElement     ui     = _pointerDataProvider.UnderCursorUiElement;
            IDropReceiver result = ui as IDropReceiver;

            if (result != null)
            {
                return(result);
            }

            TileObject to = _pointerDataProvider.UnderCursorTileObject;

            result = to as IDropReceiver;

            return(result);
        }
Esempio n. 11
0
        public static bool PlaceObject(int x, int y, int type, bool mute = false, int style = 0, int alternate = 0, int random = -1, int direction = -1)
        {
            TileObject toBePlaced;

            if (!TileObject.CanPlace(x, y, type, style, direction, out toBePlaced, false))
            {
                return(false);
            }
            toBePlaced.random = random;
            if (TileObject.Place(toBePlaced) && !mute)
            {
                WorldGen.SquareTileFrame(x, y, true);
                //   Main.PlaySound(0, x * 16, y * 16, 1, 1f, 0f);
            }
            return(false);
        }
Esempio n. 12
0
    /// <summary>
    /// Loops through all centerpoints to return the closest from the object
    /// </summary>
    /// <param name="tile">The object to search</param>
    /// <returns></returns>
    private TileObject GetClosestCenter(TileObject tile)
    {
        TileObject closest  = centerPoints[0];
        float      distance = int.MaxValue;

        foreach (TileObject center in centerPoints)
        {
            float d = Distance2(center, tile);
            if (d < distance)
            {
                closest  = center;
                distance = d;
            }
        }
        return(closest);
    }
Esempio n. 13
0
    private IEnumerator Turn(TileObject obj, float speed, DirectionEnum dir)
    {
        var rot = Direction.DirectionToDegrees(dir);

        float counter = 0;

        Quaternion rotation = Quaternion.Euler(0, rot, 0);
        Quaternion origin   = obj.transform.localRotation;

        while (counter < speed)
        {
            counter += speed * Time.deltaTime;
            obj.transform.localRotation = Quaternion.RotateTowards(origin, rotation, counter);
            yield return(null);
        }
    }
Esempio n. 14
0
    public bool TypeChange()
    {
        if (Type == TileType.Object)
        {
            name = tileObject.Name;
            return(true);
        }

        tileObject = null;
        if (Type == TileType.Water)
        {
            name = "Water";
        }
        else if (Type == TileType.WaterDeep)
        {
            name = "WaterDeep";
        }
        else if (Type == TileType.Sand)
        {
            name = "Sand";
        }
        else if (Type == TileType.GrassLand)
        {
            name = "Grass Land";
        }
        else if (Type == TileType.Forest)
        {
            name = "Forest";
        }
        else if (Type == TileType.Dirt)
        {
            name = "Dirt";
        }
        else if (Type == TileType.Stone)
        {
            name = "Stone";
        }
        else if (Type == TileType.Snow)
        {
            name = "Snow";
        }
        else if (Type == TileType.NULL)
        {
            name = "NULL";
        }
        return(false);
    }
Esempio n. 15
0
    public static TileCoordinates GenLevel(string filename)
    {
        filename = Application.streamingAssetsPath + filename;

        string[] lines = File.ReadAllLines(filename);
        int      x     = 0;
        int      y     = 0;

        foreach (string line in lines)
        {
            string[] lienOfTile = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
            x = 0;
            foreach (string tileInfo in lienOfTile)
            {
                string[] words = tileInfo.Split(',');

                ETileType tileType = ms_CharToTileType[words[0]];
                if (tileType == ETileType.None)
                {
                    x++;
                    continue;
                }
                GameObject tileGameObject = GameObject.Instantiate(RessourceManager.LoadPrefab("Tile"));
                tileGameObject.transform.position = new Vector3(x.ToWorldUnit(), y.ToWorldUnit(), 0);
                Tile tile = tileGameObject.AddComponent <Tile> ();
                tile.SetCoordinates(new TileCoordinates(x, y));
                tile.SetType(tileType);

                TileManagerProxy.Get().AddTile(tile);

                if (words.Length > 1)
                {
                    ETileObjectType tileObjectType       = (ETileObjectType)Enum.Parse(typeof(ETileObjectType), (String)words.GetValue(1), true);
                    GameObject      tileObjectGameObject = GameObject.Instantiate(RessourceManager.LoadPrefab("TileObject_" + words[1]));
                    tileObjectGameObject.transform.position = new Vector3(x.ToWorldUnit(), y.ToWorldUnit(), 0);
                    TileObject tileObject = tileObjectGameObject.GetComponent <TileObject> ();
                    tileObject.Init(tileObjectType, x, y, words.SubArray(2, -1));
                    tile.SetTileObject(tileObject);
                }

                x++;
            }
            y--;
        }

        return(new TileCoordinates(x, y));
    }
Esempio n. 16
0
        //=====================================// GRID CREATION //=====================================//

        private void CreateGameTab()
        {
            TileObject dirt = ResourceHolder.Get.GetTerrainTileObject("Plain Dirt");

            Selection = new Selection(dirt, this);

            TileObject grass = ResourceHolder.Get.GetTerrainTileObject("Plain Grass");

            TileGrid = new Tile[BoardDensity, BoardDensity];

            List <TileCategory> categories = ResourceHolder.Get.GetSelectedCategories();

            _selectorGridCreator = new PlacerSelectorGridCreator(this, categories);

            _gameGridCreator = new PlacerGridCreator(this, BoardDensity, grass);
            Grids["GameMap"] = _gameGridCreator.CreateElementsInWindow(this, BoardDensity);
        }
        private void UpdateObjectUnderCursor()
        {
            Vector2 mousePos = _mouseWorldPosition;

            RaycastHit2D[] hits = Physics2D.RaycastAll(mousePos, Vector2.zero, 0);

            TileObject result          = null;
            int        maxSortingLayer = 0;
            int        maxSortingOrder = 0;

            foreach (RaycastHit2D hit in hits)
            {
                GameObject go = hit.transform.gameObject;
                TileObject to = go.GetComponent <TileObject>();

                if (to == null)
                {
                    IChildCollider child    = go.GetComponent <IChildCollider>();
                    GameObject     parentGo = child?.Parent;
                    to = parentGo?.GetComponent <TileObject>();
                }

                SpriteRenderer spriteRenderer = go.GetComponent <SpriteRenderer>();

                if (spriteRenderer == null)
                {
                    continue;
                }

                int layerValue = SortingLayer.GetLayerValueFromID(spriteRenderer.sortingLayerID);

                if (layerValue > maxSortingLayer || result == null)
                {
                    result          = to;
                    maxSortingLayer = layerValue;
                    maxSortingOrder = 0;
                }
                else if (spriteRenderer.sortingOrder > maxSortingOrder)
                {
                    maxSortingOrder = spriteRenderer.sortingOrder;
                    result          = to;
                }
            }

            _objectUnderCursor = result;
        }
Esempio n. 18
0
    public override TileObject[,] initializeMap()
    {
        tmpMapWBorder = null;
        map           = new TileObject[width, height];
        //Map initialization.
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                map[x, y].type = roomChar;
            }
        }

        RandomFillMap();

        return(map);
    }
Esempio n. 19
0
        private void LateUpdate()
        {
            // Render all tiles around the target
            Vector2Int targetPos = new Vector2Int((int)target.position.x, (int)target.position.y);
            Dictionary <Vector2Int, TileObject> newRenderedTiles = new Dictionary <Vector2Int, TileObject>(RenderedTiles);

            foreach (Vector2Int tilePos in RenderedTiles.Keys)
            {
                if (tilePos.x > targetPos.x + renderDistance || tilePos.x < targetPos.x - renderDistance ||
                    tilePos.y > targetPos.y + renderDistance || tilePos.y < targetPos.y - renderDistance)
                {
                    TileObject tile = RenderedTiles[tilePos];
                    newRenderedTiles.Remove(tilePos);

                    // "De-activate" the tile/gameObject
                    _inactiveTiles.Enqueue(tile);
                    tile.gameObject.SetActive(false);
                }
            }

            RenderedTiles = newRenderedTiles;

            for (int x = targetPos.x - renderDistance; x < targetPos.x + renderDistance; x++)
            {
                for (int y = targetPos.y - renderDistance; y < targetPos.y + renderDistance; y++)
                {
                    Vector2Int position = new Vector2Int(x, y);
                    if (RenderedTiles.ContainsKey(position))
                    {
                        continue;
                    }
                    if (x < 0 || x >= World.Data.Width || y < 0 || y >= World.Data.Height)
                    {
                        continue;
                    }

                    Tile       tile       = World.Data.GetTile(x, y);
                    TileObject tileObject = _inactiveTiles.Dequeue();
                    tileObject.UpdateTile(tile);
                    tileObject.transform.position = new Vector3(x, y, 0);
                    tileObject.gameObject.SetActive(true);

                    RenderedTiles.Add(position, tileObject);
                }
            }
        }
Esempio n. 20
0
    public void SwitchTile(Vector2 mousepos, TileType tp, TextureType tt, TileObject to, string asset)
    {
        //check selected tile
        Vector2 vpos = GridPosition(mousepos + new Vector2(0, cellHeight / 2));
        Point   pos  = new Point((int)vpos.X, (int)vpos.Y);
        Tile    tile = Get(pos.X, pos.Y) as Tile;

        if (tile != null)
        {
            //change tile
            if (tile.TileObject == to)
            {
                tile.ChangeTile(tp, tt, asset);
            }
            else
            {
                //replace tile
                Remove(tile.Id, pos.X, pos.Y);
                Tile newtile;
                switch (to)
                {
                case TileObject.Tile:
                    newtile = new Tile(pos, asset, tp, tt);
                    break;

                case TileObject.WallTile:
                    newtile = new WallTile(pos, asset, tp, tt);
                    break;

                case TileObject.TreeTile:
                    newtile = new TreeTile(pos, asset, tp, tt);
                    break;

                case TileObject.GrassTile:
                    newtile = new GrassTile(pos, asset, tp, tt);
                    break;

                default:
                    newtile = new Tile(pos);
                    break;
                }
                Add(newtile, pos.X, pos.Y);
                newtile.ChangeTile(tp, tt, asset);
            }
        }
    }
Esempio n. 21
0
    protected void FixedUpdate()
    {
        Ray        cRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        //if the mouse hit something
        if (Physics.Raycast(cRay, out hit))
        {
            TileObject tileObject = hit.transform.gameObject.GetComponent <TileObject>();
            //if the object is a tile
            if (tileObject != null)
            {
                Tile tile = TerrainManager.Instance.TileByObject(tileObject);
                SetTexts(tile.Resources);
            }
        }
    }
Esempio n. 22
0
    void Update()
    {
        Move();
        CheckUnderTile();

        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Ray        cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            int        posX      = Mathf.FloorToInt(cameraRay.origin.x);
            int        posY      = Mathf.FloorToInt(cameraRay.origin.y);
            TileObject to        = roomManager.currentRoom.GetTileAt(posX, posY);
            if (to != null)
            {
                to.Destroy();
            }
        }
    }
Esempio n. 23
0
    private int GetDistance(TileObject tileA, TileObject tileB)
    { // <-- get the distance
        int x = tileA.x - tileB.x;
        int y = tileA.y - tileB.y;

        if (x < 0)
        {
            x *= -1;
        }

        if (y < 0)
        {
            y *= -1;
        }

        return(14 * y + 10 * (x - y));
    }
Esempio n. 24
0
    override public void CreateMap()
    {
        float scale = 7.0f;
        float tileSize = 32.0f * scale;
        _tileScale = new Vector3(scale, scale);

        //1층
        TextAsset scriptAsset = Resources.Load<TextAsset>("Data/Map1TitleSceneData_layer1");
        string[] records = scriptAsset.text.Split('\n');

        {
            string[] token = records[0].Split(',');
            _width = int.Parse(token[1]);
            _height = int.Parse(token[2]);
        }

        _tileCellList = new TileCell[_height, _width];
        for (int y = 0; y < _height; y++)
        {
            int line = y + 2;
            string[] token = records[line].Split(',');
            for (int x = 0; x < _width; x++)
            {
                int spriteIndex = int.Parse(token[x]);

                GameObject tileGameObject = GameObject.Instantiate(TileObjectPrefabs);
                tileGameObject.transform.SetParent(transform);
                tileGameObject.transform.localScale = _tileScale;
                tileGameObject.transform.localPosition = Vector3.zero;

                TileObject tileObject = tileGameObject.GetComponent<TileObject>();
                tileObject.Init(_spriteArray[spriteIndex], x, y);

                _tileCellList[y, x] = new TileCell();
                GetTileCell(x, y).Init();
                //setPosition 합치기
                float pixelWidth = _width * tileSize / 100.0f;
                float pixelHeight = _height * tileSize / 100.0f;
                //GetTileCell(x, y).SetPosition(x * tileSize / 100.0f, -y * tileSize / 100.0f);
                GetTileCell(x, y).SetPosition(x * tileSize / 100.0f - pixelWidth / 2.0f, - y * tileSize / 100.0f + pixelHeight / 2.0f);
                GetTileCell(x, y).SetTilePosition(x, y);

                GetTileCell(x, y).AddObject(eTileLayer.GROUND, tileObject);
            }
        }
    }
Esempio n. 25
0
    public void AddObjectToTile(TileObject _tileObject, int _x, int _y, bool _selectable)
    {
        if (_x > m_gridWidth - 1 || _y > m_gridHeight - 1)
        {
            Debug.LogError("Grid position out of bounds");
            return;
        }

        FloorTile tile = m_grid[_x, _y];

        if (tile == null)
        {
            return;
        }

        tile.AddObject(_tileObject, _selectable);
    }
Esempio n. 26
0
        private static void GenerateTileLayer(RoomScene room, Dictionary <string, Dictionary <string, ArrayList> > layer, LayerEnum layerEnum)
        {
            var TileDict = Systems.mapper.TileDict;

            // Loop through YData within the Layer Provided:
            foreach (KeyValuePair <string, Dictionary <string, ArrayList> > yData in layer)
            {
                short gridY = short.Parse(yData.Key);

                // Loop through XData
                foreach (KeyValuePair <string, ArrayList> xData in yData.Value)
                {
                    short gridX = short.Parse(xData.Key);

                    byte tileId  = Convert.ToByte(xData.Value[0]);
                    byte subType = Convert.ToByte(xData.Value[1]);
                    Dictionary <string, short> paramList = null;

                    if (xData.Value.Count > 2)
                    {
                        // ERRORS HERE MEAN: The json data saved a string instead of a short; e.g. {"Suit", "WhiteNinja"} instead of {"Suit", 2}
                        // To fix it, we need to run LevelConvert updates that make the appropriate changes.
                        paramList = JsonConvert.DeserializeObject <Dictionary <string, short> >(xData.Value[2].ToString());
                    }

                    // Check the TileDict to identify setup requirements. If it does, run it's setup process.
                    TileObject tile = TileDict[tileId];

                    // If the tile is considered "Pre-Setup Only" - only run its pre-setup method; don't add it to the scene.
                    if (tile.setupRules == SetupRules.PreSetupOnly)
                    {
                        (tile as dynamic).PreSetup(room, (short)(gridX + (byte)TilemapEnum.GapLeft), (short)(gridY + (byte)TilemapEnum.GapUp), tileId, subType, paramList);
                        continue;
                    }

                    RoomGenerate.AddTileToScene(room, layerEnum, gridX, gridY, tileId, subType, paramList);

                    // Post Setup
                    if (tile.setupRules >= SetupRules.SetupTile)
                    {
                        (tile as dynamic).SetupTile(room, (short)(gridX + (byte)TilemapEnum.GapLeft), (short)(gridY + (byte)TilemapEnum.GapUp));
                    }
                }
            }
        }
Esempio n. 27
0
        public TileObject GetObjectUnderPoint(int x, int y)
        {
            if (_scene == null)
            {
                return(null);
            }

            GetPositionWithOffset(x, y, out Vector2Int cell, out Vector2 offset);


            TileObject result = null;

            var cursorProjection = _renderReceiver.PixelToSfml(new Vector2i(x, y));

            for (int i = cell.X - 1; i <= cell.X + 1; i++)
            {
                for (int j = cell.Y - 1; j <= cell.Y + 1; j++)
                {
                    TileObject[] objectsNearby = _scene.GetObjects(new Vector2Int(i, j));
                    foreach (var obj in objectsNearby)
                    {
                        if (IsUnderCursor(obj, cursorProjection))
                        {
                            if (result == null)
                            {
                                result = obj;
                            }
                            else if ((int)result.Layer < (int)obj.Layer)
                            {
                                result = obj;
                            }
                            else if ((int)result.Layer == (int)obj.Layer)
                            {
                                if (result.LayerOrder <= obj.LayerOrder)
                                {
                                    result = obj;
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 28
0
        private static IList <TileObject> DeserializeTileObjects(XmlElement listRoot)
        {
            List <TileObject> result = new List <TileObject>(listRoot.ChildNodes.Count);

            foreach (var child in listRoot.ChildNodes)
            {
                if (child is XmlElement element)
                {
                    TileObject tileObject = DeserializeTileObject(element);
                    if (tileObject != null)
                    {
                        result.Add(tileObject);
                    }
                }
            }

            return(result);
        }
Esempio n. 29
0
    public static ImprovementObjectCity FindNearest(TileObject tile, Nation nation)
    {
        var cities   = nation.Cities;
        int lastCost = int.MaxValue;
        int index    = 0;

        for (int i = 0; i < cities.Count; i++)
        {
            var newPath = WorldPathfinding.FindPath(tile, cities[i].Tile);
            if (newPath.TotalCost < lastCost)
            {
                index    = i;
                lastCost = newPath.TotalCost;
            }
        }

        return(cities[index]);
    }
Esempio n. 30
0
    public void Claim(TileObject tile)
    {
        if (tile)
        {
            if (tile.Nation && tile.City)
            {
                tile.City.Unclaim(tile);
            }

            tile.SetNation(Nation, this);
            territory.Add(tile);

            if (Nation.Capital)
            {
                Nation.Capital.UpdateTerritory();
            }
        }
    }
        private void ClickOnTileObject()
        {
            Humanoid playerHumanoid = _localPlayerMob as Humanoid;

            if (playerHumanoid != null)
            {
                if (CheckVisibilityUnderCursor())
                {
                    TileObject to = _objectUnderCursor;

                    var item = to as IPlayerInteractable;
                    if (item != null && to.IsNeighbour(_localPlayerMob))
                    {
                        ((IPlayerInteractable)to).ApplyItemClient(playerHumanoid.GetItemBySlot(ActiveHand));
                    }
                }
            }
        }
Esempio n. 32
0
    private List <RiverPath> LineToNextHex(River river, TileObject from, TileObject to, int startCorner, int dir)
    {
        List <RiverPath> lines = new List <RiverPath>();

        List <int> sides = ClosestCorner(startCorner, dir, river.side);

        foreach (int side in sides)
        {
            lines.Add(new RiverPath()
            {
                from      = from,
                to        = to,
                direction = dir,
                corner    = side
            });
        }
        return(lines);
    }
    public void SetActiveTile(int x, int y)
    {
        TileObject newTile = null;

        if (objectPool.count > 0)
        {
            newTile = objectPool.Dequeue();
        }
        else
        {
            // We didn't have enough tiles store in our pool so lets make a new 1.
            newTile = Instantiate(tilePrefab);
        }
        newTile.transform.position = new Vector3(x, y, 1);   // Used 1 to put it behind my player...
        newTile.gameObject.SetActive(true);
        // The sprite here would be based off of your world data, where mine is only a white box, I use the second parameters to give it a gray-scaled color.
        newTile.UpdateSprite(terrainSprites[0], Mathf.PerlinNoise(x / 10.0f, y / 10.0f));
    }
Esempio n. 34
0
    /// <summary>
    /// Generate the map of tiles.
    /// </summary>
    /// <param name="map">Map of numbers to generate into tiles.</param>
    private void Generate(int[][] map)
    {
        GeneratedMap = new TileObject[map.Length][];

        for (int i = 0; i < map.Length; i++)
        {
            GeneratedMap[i] = new TileObject[map[i].Length];

            for (int j = 0; j < map[i].Length; j++)
            {
                // Create the tile object
                GameObject tileObject = Instantiate(tileObjectPrefab, new Vector2(i * tileSize,
                                                                                  j * tileSize), Quaternion.Euler(0, 0, 90), transform) as GameObject;
                GeneratedMap[i][j] = tileObject.GetComponent <TileObject>();
                GeneratedMap[i][j].Generate(tiles[map[i][j]], i, j);
            }
        }
    }
Esempio n. 35
0
    public void Save()
    {
        List <TileObject.SaveObject> save = new List <TileObject.SaveObject>();

        for (int x = 0; x < grid.GetWidth(); x++)
        {
            for (int y = 0; y < grid.GetHeight(); y++)
            {
                TileObject tileObject = grid.GetGridObject(x, y);
                save.Add(tileObject.Save());
            }
        }
        SaveObject saveObject = new SaveObject {
            saveObjectArray = save.ToArray()
        };

        SaveSystem.SaveObject(saveObject);
    }
Esempio n. 36
0
    public override void FromXML(XmlNode node)
    {
        if (node == null || node.Name != "objectgroup")
        {
            return;
        }
        XmlAttributeCollection attrs = node.Attributes;
        m_name = attrs["name"].Value;

        foreach (XmlNode child in node.ChildNodes)
        {
            if (child.Name == "object")
            {
                attrs = child.Attributes;
                TileObject obj = new TileObject();
                obj.m_id= Convert.ToInt32(attrs["id"].Value);
                obj.m_name = (attrs["name"] != null) ? attrs["name"].Value : "";
                obj.m_type = (attrs["type"] != null) ? attrs["type"].Value : "";
                obj.m_position.first = Convert.ToInt32(attrs["x"].Value);
                obj.m_position.second = Convert.ToInt32(attrs["y"].Value);
                obj.m_dimensions.first = attrs["width"] == null ? 0 : Convert.ToInt32(attrs["width"].Value);
                obj.m_dimensions.second = attrs["height"] == null ? 0 : Convert.ToInt32(attrs["height"].Value);
                foreach (XmlNode propsNode in child.ChildNodes)
                {
                    if (propsNode.Name == "properties")
                    {
                        foreach(XmlNode property in propsNode.ChildNodes)
                        {
                            attrs = property.Attributes;
                            if (property.Name == "property")
                            {
                                obj.m_properties[attrs["name"].Value] = attrs["value"].Value;
                            }
                        }
                    }
                }
                m_objects.Add(obj);

            }
        }
    }
Esempio n. 37
0
        //mouse up pbBackground
        private void pbBackground_MouseUp(object sender, MouseEventArgs e)
        {
            if (_SelectedPicbox == _pbEraser)
            { }
            else if (_SelectedPicbox == _pbLand)
            {
                _endPoint = new Point(e.X / MapObject.MINIMUM_WIDTH * MapObject.MINIMUM_WIDTH,
                                        e.Y / MapObject.MINIMUM_HEIGHT * MapObject.MINIMUM_HEIGHT);
                Rectangle rect = GetRectBetweenPoints(_startPoint, _endPoint);
                if (rect.Size.Height > 0 && rect.Size.Width > 0)
                {
                    TileObject tileObj = new TileObject(
                        _ListPicbox.IndexOf(_pbLand),
                        rect.Location.X + rect.Size.Width/2,
                        _MapObj.MapHeight - (rect.Location.Y + rect.Size.Height/2),
                        rect.Size.Width,
                        rect.Size.Height
                        );
                    _MapObj.ListGround.Add(tileObj);
                }
            }
            else if (_SelectedPicbox == _pbLava)
            {
                _endPoint = new Point(e.X / MapObject.MINIMUM_WIDTH * MapObject.MINIMUM_WIDTH,
                                        e.Y / MapObject.MINIMUM_HEIGHT * MapObject.MINIMUM_HEIGHT);
                Rectangle rect = GetRectBetweenPoints(_startPoint, _endPoint);
                if (rect.Size.Height > 0 && rect.Size.Width > 0)
                {
                    TileObject tileObj = new TileObject(
                        _ListPicbox.IndexOf(_pbLava),
                        rect.Location.X + rect.Size.Width / 2,
                        _MapObj.MapHeight - (rect.Location.Y + rect.Size.Height / 2),
                        rect.Size.Width,
                        MapObject.MINIMUM_HEIGHT
                        );
                    _MapObj.ListGround.Add(tileObj);
                }
            }
            else
            { }

            _IsMouseDown = false;
            if (_pbBackground != null)
                _pbBackground.Invalidate();
        }
Esempio n. 38
0
    public void AssignMovementPlaneValues(GameObject presTile, bool isClickable, bool ifAttack, TileObject parent, Movement[] planeRoute = null, int moveCost = 0, int initDamage = 0, BasicTile.Orientation knockbackDir = BasicTile.Orientation.Directionless, int knockBackValue = 0, int aoeDist = 0)
    {
        presentTile = presTile;
        route = planeRoute;
        isAttack = ifAttack;
        parentUnit = parent;
        damage = initDamage;
        movementCost = moveCost;
        planeEnabled = isClickable;
        knockbackDirection = knockbackDir;
        knockback = knockBackValue;
        aOERange = aoeDist;
        //routeLine = gameObject.AddComponent<LineRenderer>();
        /*GameObject text = new GameObject();
        coordinates = text.AddComponent<TextMesh>();
        text.transform.parent = transform;

        text.transform.localPosition += new Vector3(0f, 1f, 0f);
        text.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
        coordinates.text = "(" + presentTile.GetComponent<BasicTile>().XPosition + ", " + presentTile.GetComponent<BasicTile>().YPosition + ")";
        coordinates.fontSize = 1;*/
    }
Esempio n. 39
0
        //doc file enemy
        private void ReadFile(string path)
        {
            StreamReader sr = null;

            int temp = 0;
            int id = 0;
            int x = 0;
            int y = 0;
            int w = 0;
            int h = 0;

            try
            {
                sr = new StreamReader(path);
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Không đọc được file");
                return;
            }

            if (sr == null)
                return;

            _MapObj.ListObject.Clear();

            //list enemy here
            bool valid = true;
            while (!sr.EndOfStream)
            {
                #region ID
                do
                {
                    id = 0;
                    valid = false;
                    try
                    {
                        temp = sr.Read();
                    }
                    catch
                    {
                        sr.Close();
                        return;
                    }
                    while (temp > 47 && temp < 58)
                    {
                        id = id * 10 + (temp - 48);
                        valid = true;
                        try
                        {
                            temp = sr.Read();
                        }
                        catch
                        {
                            sr.Close();
                            return;
                        }
                    }
                } while (!sr.EndOfStream && !valid);
                #endregion

                #region X
                do
                {
                    x = 0;
                    valid = false;
                    try
                    {
                        temp = sr.Read();
                    }
                    catch
                    {
                        sr.Close();
                        return;
                    }
                    while (temp > 47 && temp < 58)
                    {
                        x = x * 10 + (temp - 48);
                        valid = true;
                        try
                        {
                            temp = sr.Read();
                        }
                        catch
                        {
                            sr.Close();
                            return;
                        }
                    }
                } while (!sr.EndOfStream && !valid);
                #endregion

                #region Y
                do
                {
                    y = 0;
                    valid = false;
                    try
                    {
                        temp = sr.Read();
                    }
                    catch
                    {
                        sr.Close();
                        return;
                    }
                    while (temp > 47 && temp < 58)
                    {
                        y = y * 10 + (temp - 48);
                        valid = true;
                        try
                        {
                            temp = sr.Read();
                        }
                        catch
                        {
                            sr.Close();
                            return;
                        }
                    }
                } while (!sr.EndOfStream && !valid);
                #endregion

                #region Width
                do
                {
                    w = 0;
                    valid = false;
                    try
                    {
                        temp = sr.Read();
                    }
                    catch
                    {
                        sr.Close();
                        return;
                    }
                    while (temp > 47 && temp < 58)
                    {
                        w = w * 10 + (temp - 48);
                        valid = true;
                        try
                        {
                            temp = sr.Read();
                        }
                        catch
                        {
                            sr.Close();
                            return;
                        }
                    }
                } while (!sr.EndOfStream && !valid);
                #endregion

                #region Height
                do
                {
                    h = 0;
                    valid = false;
                    try
                    {
                        temp = sr.Read();
                    }
                    catch
                    {
                        sr.Close();
                        return;
                    }
                    while (temp > 47 && temp < 58)
                    {
                        h = h * 10 + (temp - 48);
                        valid = true;
                        try
                        {
                            temp = sr.Read();
                        }
                        catch
                        {
                            sr.Close();
                            return;
                        }
                    }
                } while (!sr.EndOfStream && !valid);
                #endregion

                #region NOTE
                string note = null;
                try
                {
                    note = sr.ReadLine();
                }
                catch
                {
                    sr.Close();
                    return;
                }
                #endregion

                try
                {

                    if (id < 1)
                    { }
                    else if (id == (int)eOBJECTID.GROUND || id == (int)eOBJECTID.LAVA)
                    {
                        TileObject tileObj = new TileObject(id, x, y, w, h);
                        if (note != null)
                            tileObj.Note = note;
                        _MapObj.ListGround.Add(tileObj);
                    }
                    else
                    {
                        if (id < _ListPicbox.Count)
                        {
                            TileObject tileObj = new TileObject(id, x, y, w, h);
                            if (!string.IsNullOrEmpty(note) && note != "-1")
                                tileObj.Note = note;
                            _MapObj.ListObject.Add(tileObj);
                        }
                    }
                }
                catch
                { }
            }
            sr.Close();
        }
Esempio n. 40
0
 public static bool CallPostPlacementPlayerHook(int tileX, int tileY, int type, int style, int dir, TileObject data)
 {
     TileObjectData tileData = TileObjectData.GetTileData(type, style, data.alternate);
     if (tileData == null || tileData._placementHooks == null || tileData._placementHooks.postPlaceMyPlayer.hook == null)
     {
         return false;
     }
     PlacementHook postPlaceMyPlayer = tileData._placementHooks.postPlaceMyPlayer;
     if (postPlaceMyPlayer.processedCoordinates)
     {
         tileX -= (int)tileData.Origin.X;
         tileY -= (int)tileData.Origin.Y;
     }
     return postPlaceMyPlayer.hook(tileX, tileY, type, style, dir) == postPlaceMyPlayer.badReturn;
 }
Esempio n. 41
0
    public void InitializeTile()
    {
        grid = GameObject.Find("Grid").GetComponent<LevelGrid>();
        heightVariationProgress = 0f;
        continuousHeight = presentHeight;
        characterStepping = null;
        isOccupied = false;

        randomHeightVariation = Random.Range(-randomHeightVariationRange, randomHeightVariationRange);

        if (isSpawn)
        {
            grid.spawnTiles.Add (this);
        }

        if (Application.isEditor)
        {
            int i = gameObject.transform.childCount;
            while (i > 0){
                DestroyImmediate(gameObject.transform.GetChild(0).gameObject);
                i--;
            }
        }
        else
        {
            if (gameObject.transform.childCount > 0)
                Destroy(gameObject.transform.GetChild(0).gameObject);
            if (gameObject.transform.childCount > 0)
                Destroy(gameObject.transform.GetChild(1).gameObject);
        }

        //foundation = Instantiate(grid.emptyTile);

        if (type == TileKind.Empty)
        {
            foundation = Instantiate(grid.emptyTile);
            foundation.name = "foundation";
            foundation.transform.parent = transform;
            foundation.transform.localPosition = Vector3.zero;
        }

        else if (type == TileKind.Flat)
        {
            foundation = Instantiate(grid.foundation);
            foundation.name = "foundation";
            foundation.transform.parent = transform;
            foundation.transform.localPosition = Vector3.zero;
            //foundation.GetComponent<MeshRenderer>().material = grid.tileMaterials[1];
        }

        else if (type == TileKind.Stair)
        {
            top = Instantiate(grid.stair);
            top.name = "top";
            top.transform.parent = transform;
            top.transform.localPosition = Vector3.zero;

            foundation = Instantiate(grid.foundation);
            foundation.name = "foundation";
            foundation.transform.parent = transform;
            foundation.transform.localPosition = Vector3.zero;
            foundation.transform.localPosition = new Vector3(0f, -0.5f, 0f);
            top.transform.localPosition = new Vector3(0f, 0.25f, 0f);

            switch (orientation)
            {
                case Orientation.Forward:
                    top.transform.localRotation = Quaternion.Euler(0f, 270f, 0f);
                    break;

                case Orientation.Backward:
                    top.transform.localRotation = Quaternion.Euler(0f, 90f, 0f);
                    break;

                case Orientation.Right:
                    top.transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
                    break;

                case Orientation.Left:
                    top.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
                    break;

                case Orientation.Directionless:
                    top.transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
                    break;
            }
        }
    }
Esempio n. 42
0
        /// <summary>
        /// insert node
        /// </summary>
        public static void InsertNode(Node node, TileObject obj)
        {
            //if object doesn't belong to node, then return
            if (!Box.IsIntersect(node.BoundaryBox, obj.MovementRangeBox))
                return;

            //if node covers all screenhight and screenwidth, then divide it into 4 subnodes
            if (node.BoundaryBox.Width >= SCREEN_WIDTH + 6 && node.BoundaryBox.Height >= SCREEN_HEIGHT + 6)
            {
                if (node._Tl == null)
                    node._Tl = new Node(node._NodeId, REGION.TOP_LEFT, node.BoundaryBox);
                if (node._Tr == null)
                    node._Tr = new Node(node._NodeId, REGION.TOP_RIGHT, node.BoundaryBox);
                if (node._Bl == null)
                    node._Bl = new Node(node._NodeId, REGION.BOT_LEFT, node.BoundaryBox);
                if (node._Br == null)
                    node._Br = new Node(node._NodeId, REGION.BOT_RIGHT, node.BoundaryBox);

                int left, right, top, bot;
                left = obj.MovementRangeBox.X - obj.MovementRangeBox.Width / 2;
                right = obj.MovementRangeBox.X + obj.MovementRangeBox.Width / 2;
                top = obj.MovementRangeBox.Y + obj.MovementRangeBox.Height / 2;
                bot = obj.MovementRangeBox.Y - obj.MovementRangeBox.Height / 2;
                //if object places in two diagonals, then add it to node
                if ((left <= node.BoundaryBox.X && right >= node.BoundaryBox.X)
                    || (bot <= node.BoundaryBox.Y && top >= node.BoundaryBox.Y))
                {
                    node.ListObject.Add(obj);
                }
                else
                {
                    //insert each subnode to node
                    InsertNode(node._Tl, obj);
                    InsertNode(node._Tr, obj);
                    InsertNode(node._Bl, obj);
                    InsertNode(node._Br, obj);
                }
            }
            //else if node just covers enough screenwidth or screenheight, then add obj to node
            else
                node.ListObject.Add(obj);
        }
Esempio n. 43
0
        //mouse down pbBackground
        private void pbBackground_MouseDown(object sender, MouseEventArgs e)
        {
            _IsMouseDown = true;
            if (_SelectedObj != null)
                _SelectedObj = null;
            if (_SelectedPicbox == _pbEraser)
            {
                TileObject enemyObj = _MapObj.GetObjectAtPoint(e.Location.X, _MapObj.MapHeight - e.Location.Y);
                if (enemyObj != null)
                    _MapObj.ListObject.Remove(enemyObj);

                TileObject groundObj = _MapObj.GetGroundAtPoint(e.Location.X, _MapObj.MapHeight - e.Location.Y);
                    if (groundObj != null)
                        _MapObj.ListGround.Remove(groundObj);
            }
            else if (_SelectedPicbox == _pbLand || _SelectedPicbox == _pbLava)
            {
                _startPoint = new Point(e.X / MapObject.MINIMUM_WIDTH * MapObject.MINIMUM_WIDTH,
                    e.Y / MapObject.MINIMUM_HEIGHT * MapObject.MINIMUM_HEIGHT);
            }
            else
            {
                int id = _ListPicbox.IndexOf(_SelectedPicbox);
                int x = e.Location.X;
                int y = _MapObj.MapHeight - e.Location.Y;
                TileObject enemyObj = _MapObj.GetObjectAtPoint(x, y);
                if (enemyObj != null)
                {
                    if (enemyObj.Id != id)
                    {
                        enemyObj.Id = id;
                        enemyObj.BoundaryBox.Width = _SelectedPicbox.Image.Width * 2;
                        enemyObj.BoundaryBox.Height = _SelectedPicbox.Image.Height * 2;
                        if (enemyObj.BoundaryBox.Width == MapObject.COLUMN_SIZE
                            && enemyObj.BoundaryBox.Height == MapObject.ROW_SIZE)
                        {
                            enemyObj.BoundaryBox.X = (x / MapObject.COLUMN_SIZE) * MapObject.COLUMN_SIZE + MapObject.COLUMN_SIZE / 2;
                            enemyObj.BoundaryBox.Y = (y / MapObject.ROW_SIZE) * MapObject.ROW_SIZE + MapObject.ROW_SIZE / 2;
                        }

                        _SelectedObj = enemyObj;
                        _txtNote.Text = _SelectedObj.Note;
                    }
                    else
                    {
                        _SelectedObj = enemyObj;
                        _txtNote.Text = _SelectedObj.Note;
                    }
                }
                else
                {
                    if (_SelectedPicbox.Image.Width * 2 == MapObject.COLUMN_SIZE
                            && _SelectedPicbox.Image.Width * 2 == MapObject.ROW_SIZE)
                    {
                        enemyObj = new TileObject(
                            id,
                            (x / MapObject.COLUMN_SIZE) * MapObject.COLUMN_SIZE + MapObject.COLUMN_SIZE / 2,
                            (y / MapObject.ROW_SIZE) * MapObject.ROW_SIZE + MapObject.ROW_SIZE / 2,
                            _SelectedPicbox.Image.Width * 2,
                            _SelectedPicbox.Image.Height * 2
                            );
                    }
                    else
                    {
                        enemyObj = new TileObject(id, x, y,
                            _SelectedPicbox.Image.Width * 2,
                            _SelectedPicbox.Image.Height * 2
                            );
                    }
                    _MapObj.ListObject.Add(enemyObj);
                    _SelectedObj = enemyObj;
                    _txtNote.Text = _SelectedObj.Note;
                }
            }

            if (_pbBackground != null)
                _pbBackground.Invalidate();
        }
Esempio n. 44
0
	protected void AddTileToGrid (int xKey, int yKey, TileObject to) {

		// if the xKey does not exist in the dictionary, add it
		if (!tileGrid.ContainsKey (xKey)) {
			tileGrid.Add (xKey, new Dictionary<int, TileObject> ());
		}
		
		// now add the terrain object to the sub dictionary
		try {
			tileGrid[xKey].Add (yKey, to);
		} catch {
			Debug.LogError ("Index of Tile (" + xKey + ", " + yKey + ") already exists.");
		}
	}
Esempio n. 45
0
 public List<TileObject> GetTiles()
 {
     var tiles = new List<TileObject>();
     foreach (var m in maps) {
         for (int i = 0; i < m.Value.Length; i++) {
             var x = i / MapSize;
             var y = i - (x * MapSize);
             TileObject t = new TileObject((MapSize * m.Key + new Vector2int(x, y)), m.Value[i]);
             tiles.Add(t);
         }
     }
     return tiles;
 }
Esempio n. 46
0
    void StateManager()
    {
        ClearMoves();

        int xPos = presentTile.GetComponent<BasicTile>().XPosition,
            yPos = presentTile.GetComponent<BasicTile>().YPosition;

        MovementPlane.Movement[] startRoute = new MovementPlane.Movement[0];

        possibleMoves = new GameObject[grid.xSize * grid.ySize];

        routesFound = 0;
        parsedMoves = 0;

        FindMoves(xPos, yPos, startRoute, routesFound, detectionRange, detectionRange, true);

        for(int i = 0; i < objectsWithinRange.Count; i++)
        {
            if (objectsWithinRange[i].team != team)
            {
                targetObject = objectsWithinRange[i];
                break;
            }
        }
        if (targetObject != null)
        {
            for (int i = 0; i < possibleMoves.Length; i++)
            {
                if (targetObject.WithinZMovesFromThis(3, possibleMoves[i].GetComponent<MovementPlane>().PresentTile.GetComponent<BasicTile>(), false))// && targetObject.presentTile.GetComponent<BasicTile>().Accessible(possibleMoves[i].GetComponent<MovementPlane>().presentTile.GetComponent<BasicTile>(), true))
                {
                    isMoving = true;
                    /*if (possibleMoves[i].GetComponent<MovementPlane>().movementCost <= maxMovementPoints)
                    {
                        StartCoroutine(FollowRoute(TileObject.TruncateRoute(possibleMoves[i].GetComponent<MovementPlane>().route, maxMovementPoints, true)));
                    }
                    else*/
                    StartCoroutine(FollowRoute(TileObject.TruncateRoute(possibleMoves[i].GetComponent<MovementPlane>().Route, maxMovementPoints, false)));
                    ClearMoves();
                    break;
                }
            }
        }
    }
Esempio n. 47
0
        public static List<TileObject> getTileObjectLayout(ContentManager content, string filename)
        {
            TileLayer tLayer = TileLayer.FromFile(content, filename);
            List<TileObject> objList = new List<TileObject>();

            int spawnMapWidth = tLayer.map.GetLength(1);
            int spawnMapHeight = tLayer.map.GetLength(0);

            for (int x = 0; x < spawnMapWidth; x++)
            {
                for (int y = 0; y < spawnMapHeight; y++)
                {
                    int textIndex = tLayer.map[y, x];

                    ObjectType objtype = ObjectType.NORMAL;

                    if (textIndex == 0)
                    {
                        continue;
                    }

                    if (textIndex == 1)
                    {
                        objtype = ObjectType.CRATE;
                    }

                    if (textIndex == 2)
                    {
                        objtype = ObjectType.PICKUP;
                    }

                    if (textIndex == 3)
                    {
                        objtype = ObjectType.COLLISION;
                    }

                    if (textIndex == 4)
                    {
                        objtype = ObjectType.COLLISION;
                    }

                    if (textIndex == 5)
                    {
                        objtype = ObjectType.COLLISION;
                    }

                    if (textIndex == 6)
                    {
                        objtype = ObjectType.DESTRUCTIBLE;
                    }

                    TileObject tobj = new TileObject(tLayer.tileTextures[textIndex - 1], objtype, new Vector2(x * tLayer.TileWidth, y * tLayer.TileHeight));
                    objList.Add(tobj);

                }
            }

            return objList;
        }
Esempio n. 48
0
 public void SetTile(TileObject above, TileObject below, TileObject left, TileObject right)
 {
     // set each of the tile references
     aboveTile = SetTileReference (above, Vector3.up);
     if (above != null) {
         above.belowTile = above.SetTileReference (this, Vector3.down);
     }
     belowTile = SetTileReference (below, Vector3.down);
     if (below != null) {
         below.aboveTile = below.SetTileReference (this, Vector3.up);
     }
     leftTile = SetTileReference (left, Vector3.left);
     if (left != null) {
         left.rightTile = left.SetTileReference (this, Vector3.right);
     }
     rightTile = SetTileReference (right, Vector3.right);
     if (right != null) {
         right.leftTile = right.SetTileReference (this, Vector3.left);
     }
 }
Esempio n. 49
0
	protected void SetTileObject (int xKey, int yKey, TileObject newTile) { 

		// we can't proceed without a tile grid;
		if (tileParent == null) {
			return;
		}
		if (tileGrid == null) {
			InitTileGrid ();
		}

		// get the tiles around this new tile
		TileObject toAbove = null;
		if (tileGrid.ContainsKey (xKey)) {
			tileGrid[xKey].TryGetValue ((yKey + 1), out toAbove);
		}
		TileObject toBelow = null;
		if (tileGrid.ContainsKey (xKey)) {
			tileGrid[xKey].TryGetValue (yKey - 1, out toBelow);
		}
		TileObject toLeft = null;
		if (tileGrid.ContainsKey (xKey - 1)) {
			tileGrid[xKey - 1].TryGetValue (yKey, out toLeft);
		}
		TileObject toRight = null;
		if (tileGrid.ContainsKey (xKey + 1)) {
			tileGrid[xKey + 1].TryGetValue (yKey, out toRight);
		}

		string tileName = "";
		if (newTile != null) {
			tileName = newTile.name + " (" + xKey + ", " + yKey + ")";
		}

		// get the tile object we're working with
		if (tileGrid.ContainsKey (xKey) && tileGrid [xKey].ContainsKey (yKey)) {
			if (newTile == null) {
				// no new tile? Then just refresh the one at its current place
				tileGrid[xKey][yKey].SetTile (toAbove, toBelow, toLeft, toRight, spriteLayerOrder);
				return;
			}

			// if a tile exists at that index, kill it
			if (tileGrid [xKey] [yKey].name != tileName) {
				DestroyImmediate (tileGrid [xKey] [yKey].gameObject);
				tileGrid [xKey].Remove (yKey);
			} else {
				return;
			}
		}

		// instatiate the new tile
		if (newTile != null) {
			TileObject to = (TileObject)Instantiate (newTile, new Vector3 (xKey + 0.5F, yKey + 0.5F, 0.0F), Quaternion.Euler (Vector3.zero));
			to.name = tileName;
		
			// set up the tile
			to.SetTile (toAbove, toBelow, toLeft, toRight, spriteLayerOrder);
			to.transform.SetParent (tileParent);
			AddTileToGrid (xKey, yKey, to);
		}
	}
Esempio n. 50
0
    public TileObject SetTileReference(TileObject tileReference, Vector3 pos)
    {
        Transform child = transform.FindChild (getSpriteName(pos));

        if (tileReference != null && child != null) {
            DestroyImmediate (child.gameObject);
        } else if (tileReference == null && child == null) {
            CreateSubSprite (pos);
        }

        return tileReference;
    }
Esempio n. 51
0
	//_______________________________________________ [GUI FUNCTIONS]
	
	protected void OnGUI () {

		// set this script to visible
		if (!isVisible) {
			if (tileParent != null) {
				InitTileGrid ();
			}
		}
		isVisible = true;


		
		// ______________________________________ [ TILE OPTIONS ]

		GUILayout.Label("Tile Settings", EditorStyles.boldLabel);
		GUILayout.BeginVertical("box");
		
		EditorGUILayout.BeginHorizontal ();
		Transform tempTerrainHolder = (Transform) EditorGUILayout.ObjectField ("Tile Parent", tileParent, typeof (Transform), true);
		if (tileParent != tempTerrainHolder) {
			tileParent = tempTerrainHolder;
			tileParent.position = Vector3.zero;
			if (tileParent != null) {
				InitTileGrid ();
			}
		}
		EditorGUILayout.EndHorizontal ();
		
		EditorGUILayout.BeginHorizontal ();
		spriteLayerOrder = EditorGUILayout.IntField ("Sprite Order Layer", spriteLayerOrder);
		EditorGUILayout.EndHorizontal ();
		
		EditorGUILayout.BeginHorizontal ();
		if (GUILayout.Button ("Refresh Tiles") && tileParent != null) {
			InitTileGrid ();
			RefreshGridTiles ();
		}
		EditorGUILayout.EndHorizontal ();
		
		GUILayout.EndVertical ();
		GUILayout.Space (5);

		
		
		// ______________________________________ [ PAINTING ]

		GUILayout.Box(GUIContent.none, "box", GUILayout.ExpandWidth(true), GUILayout.Height(1f));
		GUILayout.Label("Tile Painting", EditorStyles.boldLabel);
		
		
		
		
		// ______________________________________ [ EDIT OPTIONS ]
		
		// show the edit types
		GUIStyle editTypeStyle = new GUIStyle ();
		editTypeStyle.padding = new RectOffset (5, 5, 1, 1);
		EditorGUILayout.BeginVertical (editTypeStyle);
		GUIStyle editTypeButtonStyle = GUI.skin.button; 
		editTypeButtonStyle.margin = new RectOffset (0, 0, 0, 0);
		EditType tempEditType = (EditType) GUILayout.SelectionGrid ((int)editType, 
		                                                            Enum.GetNames (typeof(EditType)), 
		                                                            Enum.GetValues (typeof(EditType)).Length, 
		                                                            editTypeButtonStyle, 
		                                                            GUILayout.Height (22));
		if (editType != tempEditType) {
			editType = tempEditType;
			if (tileParent != null) {
				InitTileGrid ();
			}
		}
		EditorGUILayout.EndVertical ();
		
		// show the edit modes
		GUIStyle editModeStyle = new GUIStyle ();
		editModeStyle.padding = new RectOffset (5, 5, 1, 1);
		EditorGUILayout.BeginVertical (editModeStyle);
		GUIStyle editModeButtonStyle = GUI.skin.button; 
		editModeButtonStyle.margin = new RectOffset (0, 0, 0, 0);
		editMode = (EditMode) GUILayout.SelectionGrid ((int)editMode, 
		                                               Enum.GetNames (typeof(EditMode)), 
		                                               Enum.GetValues (typeof(EditMode)).Length, 
		                                               editModeButtonStyle, 
		                                               GUILayout.Height (16));
		EditorGUILayout.EndVertical ();



		// ______________________________________ [ CATEGORIES ]
		string[] terrainCategoryFullPaths = AssetDatabase.GetSubFolders ("Assets/Prefabs/Environment/Tiles");
		string[] terrainCategories = new string[terrainCategoryFullPaths.Length];
		for (int i = 0; i < terrainCategories.Length; i++) {
			terrainCategories[i] = Path.GetFileName (terrainCategoryFullPaths[i]);
		}
		
		EditorGUILayout.BeginHorizontal ();
		selectedTerrainCategory = EditorGUILayout.Popup ("Tile Category", selectedTerrainCategory, terrainCategories);
		EditorGUILayout.EndHorizontal ();



		// ______________________________________ [ TILES ]
		GUIStyle prefabSelectionGroup = new GUIStyle (GUI.skin.box);
		prefabSelectionGroup.padding = new RectOffset (1, 1, 1, 1);
		prefabSelectionGroup.margin = new RectOffset (10, 10, 10, 0);
//		EditorGUILayout.BeginVertical(prefabSelectionGroup);
		scrollPos = EditorGUILayout.BeginScrollView(scrollPos, prefabSelectionGroup, GUILayout.Width (this.position.width - 20), GUILayout.Height (120));

		// add in prefabs in the chosen category
		GUIStyle prefabButtonGroup = new GUIStyle (GUI.skin.box);
		prefabButtonGroup.padding = new RectOffset (1, 1, 2, 1);
		prefabButtonGroup.margin = new RectOffset (0, 0, 0, 0);
		prefabButtonGroup.border = new RectOffset (3, 3, 3, 3);
		Color originalColor = GUI.backgroundColor;

		DirectoryInfo info = new DirectoryInfo(terrainCategoryFullPaths[0]);
		FileInfo[] fileInfo = info.GetFiles();

		int buttonsPerLine = (int)((this.position.width - 20) / 40);
		int buttonIncrementer = 0;
		bool foundSelected = false;
		EditorGUILayout.BeginHorizontal();

		for (int i = 0; i < fileInfo.Length; i++) {

			// get the Terrain Object
			string[] splitOptions = new string[1];
			splitOptions[0] = "Assets/";
			string path = fileInfo[i].FullName.Split (splitOptions, StringSplitOptions.None)[1];
			TileObject to = (TileObject)AssetDatabase.LoadAssetAtPath ("Assets/" + path, typeof(TileObject));

			if (to != null) {
				buttonIncrementer++;
				if (buttonIncrementer > buttonsPerLine) {
					buttonIncrementer = 0;
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
				}
				GUIContent buttonContent = new GUIContent (to.CenterSprites[0].texture);

				if (selectedTile != null && selectedTile.name == to.name) {
					foundSelected = true;
					GUI.backgroundColor = new Color (0, (210F/255F), (210F/255F));
				} else {
					GUI.backgroundColor = Color.black;
				}
				if (GUILayout.Button (buttonContent, prefabButtonGroup, GUILayout.Width (36), GUILayout.Height (36))) {
					selectedTile = to;
					foundSelected = true;
				}
			}
		}
		EditorGUILayout.EndHorizontal();

		GUI.backgroundColor = originalColor;

		EditorGUILayout.EndScrollView();

		if (!foundSelected) {
			selectedTile = null;
		}
	}
Esempio n. 52
0
 void Awake()
 {
     tileObject = GetComponentInChildren<TileObject> ();
     reserved = !passable;
 }
Esempio n. 53
0
 // Use this for initialization
 void Start()
 {
     ownerObject = gameObject.GetComponent<TileObject>();
     auraEffect = new Effect("test effect", 2, 0, 0, 0, 0, 1);
     auraEnabled = true;
 }