ToString() public method

public ToString ( ) : string
return string
Example #1
0
    protected virtual IEnumerator TakePartialScreenshot()
    {
        ScreenCapture.CaptureScreenshot(captureFilename);
        Texture2D tex = ScreenCapture.CaptureScreenshotAsTexture();

        yield return(new WaitForEndOfFrame());

        yield return(new WaitForEndOfFrame()); // Wait image is done

        // Crop
        Debug.Log("screen: " + Screen.width + "x" + Screen.height + "  res:" + Screen.safeArea.ToString());
        Vector2Int fullSize  = new Vector2Int(Screen.width, Screen.height);
        Vector2Int cropStart = new Vector2Int(
            Mathf.FloorToInt(fullSize.x * partialViewport.x),
            Mathf.FloorToInt(fullSize.y * partialViewport.y)
            );
        Vector2Int cropSize = new Vector2Int(
            Mathf.FloorToInt(fullSize.x * partialViewport.width),
            Mathf.FloorToInt(fullSize.y * partialViewport.height)
            );

        Texture2D finalTex = new Texture2D(cropSize.x, cropSize.y);

        Color[] cropPixels = tex.GetPixels(cropStart.x, cropStart.y, cropSize.x, cropSize.y);
        finalTex.SetPixels(cropPixels);

        //Rect screenRect = Rect.MinMaxRect(
        //    Mathf.FloorToInt(fullSize.x * partialViewport.x),
        //    Mathf.FloorToInt(fullSize.y * partialViewport.y),
        //    Mathf.FloorToInt(fullSize.x * partialViewport.xMax),
        //    Mathf.FloorToInt(fullSize.y * partialViewport.yMax)
        //);
        //finalTex.ReadPixels(screenRect, 0, 0); // PROBLEM :: This includes grey area of Game view

        // Save
        byte[] bytes = finalTex.EncodeToPNG();
        System.IO.File.WriteAllBytes(captureFilename, bytes);

        Debug.Log("Taken Partial Screenshot at: " + captureFilename + " ::  " + fullSize.ToString() + " -> " + cropStart.ToString() + " " + cropSize.ToString());
        //Debug.Log("Taken Partial Screenshot at: " + captureFilename + " ::  "+fullSize.ToString()+" -> "+screenRect.ToString());
        yield break;
    }
Example #2
0
    // public void Awake()
    // {

    // }

    public void Start()
    {
        GameObject grid = GameObject.Find("Grid");
        Vector3    pos  = new Vector3(
            chunkPos.x * ChunkManager.Chunk2GlobalRate,
            0,
            chunkPos.y * ChunkManager.Chunk2GlobalRate
            );

        tilesTilemap      = Instantiate(Resources.Load <GameObject>("Tiles/EmptyTilemap"), pos, Quaternion.identity, grid.transform);
        tilesTilemap.name = "Chunk_" + chunkPos.ToString();

        NPCsRoot = GameObject.Find("NPCs");
        loader   = GameObject.Find("GameManager").GetComponent <LoadManager>();
        InitializeTiles();
        InstantiateEnvironmentObjects();
        InstantiateNPCs();
        InitialzeInventories();
        InitializeEnemies();
    }
Example #3
0
    void CreateTile(Vector2Int tile, TileType id)
    {
        if (id == TileType.Wall)
        {
            return;
        }

        GameObject prefab = null;
        GameObject go     = null;

        if (id == TileType.Pellet || id == TileType.Wrap)
        {
            prefab = prefabPellet;
        }
        if (id == TileType.Powerup)
        {
            prefab = prefabPowerUp;
        }

        if (prefab != null)
        {
            go = GameObject.Instantiate(prefab, pelletsContainer);
            go.transform.localPosition = (Vector2)tile;
#if UNITY_EDITOR
            go.name = TileType.Pellet.ToString() + tile.ToString();
#endif
        }

        var wTile = new WalkableTile(tile, id, go);
        if (id == TileType.Tunnel || id == TileType.Wrap)
        {
            wTile.IsTunnel = true;
        }

        if ((tile.x == 14 || tile.x == 17) && (tile.y == 7 || tile.y == 19))
        {
            wTile.IsUpLocked = true;
        }

        walkableTiles.Add(Utils.TilePosToKey(tile), wTile);
    }
Example #4
0
    private GameObject GetChunkGameObject(Vector2Int chunkIndex)
    {
        string    name           = "Chunk " + chunkIndex.ToString();
        Transform childTransform = transform.Find(name);

        if (childTransform == null)
        {
            GameObject obj = new GameObject(name);
            obj.AddComponent <MeshFilter>();
            obj.AddComponent <MeshRenderer>().sharedMaterial = material;
            obj.AddComponent <MeshCollider>();
            obj.transform.parent = transform;
            obj.transform.Translate(new Vector3(Chunk.WIDTH * chunkIndex.x, 0, Chunk.WIDTH * chunkIndex.y));
            AddChunkBorderLines(chunkIndex, obj);
            return(obj);
        }
        else
        {
            return(childTransform.gameObject);
        }
    }
Example #5
0
    private string OffsetToSide(Vector2Int offset)
    {
        if (offset.x > 0)
        {
            return(ANIMATOR_RIGHT_SIDE_KEY);
        }
        else if (offset.x < 0)
        {
            return(ANIMATOR_LEFT_SIDE_KEY);
        }
        else if (offset.y > 0)
        {
            return(ANIMATOR_TOP_SIDE_KEY);
        }
        else if (offset.y < 0)
        {
            return(ANIMATOR_BOTTOM_SIDE_KEY);
        }

        throw new Exception($"No side for this offset: {offset.ToString()}");
    }
Example #6
0
 public static T GetData <T>(this T[,] array, Vector2Int index)
 {
     if (array == null || array.LongLength < 1)
     {
         Debug.LogError("数组为空或元素为0");
         return(default(T));
     }
     else
     {
         if (index.x >= 0 && index.x < array.GetLength(0) && index.y >= 0 && index.y < array.GetLength(1))
         {
             return(array[index.x, index.y]);
         }
         else
         {
             Debug.LogError(string.Format("下标越界,无法获取数据,数组={0},{1},index ={2}",
                                          array.GetLength(0), array.GetLength(1), index.ToString()));
             return(default(T));
         }
     }
 }
Example #7
0
    private Vector2Int CalculateNewGridIndex()
    {
        var heightIndex = GameManager.Instance.CurrentLevel.GridHeight - 1;

        while (!GridManager.Instance.HexArray[GridIndex.x, heightIndex - 1])
        {
            heightIndex--;

            // If not reached to bottom, continue.
            if (heightIndex > 0)
            {
                continue;
            }
            Debug.LogError("This column is not empty." + GridIndex.ToString());
            heightIndex = GameManager.Instance.CurrentLevel.GridHeight - 1;
            break;
        }

        GridIndex = new Vector2Int(GridIndex.x, heightIndex);
        return(GridIndex);
    }
Example #8
0
        public static Chunk Load(Vector2Int pos)
        {
            string path = Settings.chunkSaveFolder + pos.ToString() + ".chunk";

            if (!File.Exists(path))
            {
                return(null);
            }

            Chunk c = JsonUtility.FromJson <Chunk>(File.ReadAllText(path));

            c.Generated = true;
            foreach (var section in c.sections)
            {
                section.parent = c;
            }

            c.HeightMap = new HeightMap(c.Pos);
            c.HeightMap.SetHeights(c);
            return(c);
        }
Example #9
0
        //Made for mole area checking
        int GetMoleCount(int idx, Vector2Int loc)
        {
            List <CBldg> untrackedBldgs = new List <CBldg> {
                CBldg.empty
            };
            int ret = 0;

            for (int x = -1; x < 2; x++)
            {
                for (int y = -1; y < 2; y++)
                {
                    Vector2Int newLoc = new Vector2Int(loc.x + x, loc.y + y);
                    Debug.Log("Molecounting at loc " + newLoc.ToString() + " player: " + idx.ToString());
                    if (CheckLocInRange(newLoc) && !untrackedBldgs.Contains(cells[idx][newLoc.x, newLoc.y].GetCellStruct(0).bldg))
                    {
                        ret++;
                    }
                }
            }
            return(ret);
        }
Example #10
0
    public bool OnTurnStart()
    {
        if (health.x <= 0)
        {
            return(false);
        }
        bool startTurn = true;

        if (modifiers.IsStunned)
        {
            startTurn = false;
            modifiers.ClearStun();
        }
        int damage = 0;

        foreach (StatusEffect e in modifiers.Bleed)
        {
            damage += e.ApplyOverTime(unit);
        }
        if (damage > 0)
        {
            unit.CreatePopUpText(damage.ToString(), ColorPallete.GetColor("Red"));
        }
        int stress = 0;

        foreach (StatusEffect e in modifiers.Terror)
        {
            stress += e.ApplyOverTime(unit);
        }
        if (stress > 0)
        {
            unit.CreatePopUpText(stress.ToString(), ColorPallete.GetColor("Purple"));
        }
        modifiers.OnTurnBegin();
        if (health.x <= 0)
        {
            return(false);
        }
        return(startTurn);
    }
 public ActionInfo GetActionInfo(Vector2Int position)
 {
     if ((possibleActions & ActionType.Walk) == ActionType.Walk)
     {
         LinkedList <AStarPathNode> path = AStarManager.GetInstance().Search(GridTransform.Position, position);
         if (path == null || path.Count <= 1)
         {
             Debug.LogWarning("Couldn't find path to " + position.ToString());
             return(null);
         }
         if (path.Count - 1 > Stat.MovePoints.Value)
         {
             Debug.LogWarning("Not enough move points");
             return(null);
         }
         ActionInfo actionInfo = new ActionInfo();
         actionInfo.ActionList.Add(new MovingAction(path.Count - 1, path));
         return(actionInfo);
     }
     Debug.LogWarning("Can't walk");
     return(null);
 }
Example #12
0
    Chunk GenerateChunk(Vector2Int chunkPosition)
    {
        if (chunks.ContainsKey(chunkPosition))
        {
            return(chunks[chunkPosition]);
        }

        GameObject chunkGameObject = new GameObject(chunkPosition.ToString());

        chunkGameObject.transform.SetParent(transform);
        chunkGameObject.transform.position = ChunkToWorld(chunkPosition);

        Chunk newChunk = chunkGameObject.AddComponent <Chunk>();

        newChunk.Init(chunkPosition, chunkSize, chunkScale);
        newChunk.SetMaterial(mapMaterial);
        newChunk.SetInterpolation(enableInterpolation);
        newChunk.SetGreedyMeshing(enableGreedyMeshing);
        newChunk.SetTriangleIndexing(enableTriangleIndexing);

        chunks.Add(chunkPosition, newChunk);
        return(newChunk);
    }
Example #13
0
 public void RefreshMaze()
 {
     //Instantiates white squares to represent the cells occupied
     //by the current maze.
     //Instantiates only cells that have not already been instantiated.
     foreach (WilsonCell c in MazeObject.maze)
     {
         Vector2Int vec = c.vec;
         if (!UIMaze.Contains(vec))
         {
             UIMaze.Add(vec);
             GameObject    newCell      = Instantiate(UIRect, this.gameObject.transform);
             RectTransform newCellTrans = newCell.GetComponent <RectTransform>();
             //set size of cell in pixels
             newCellTrans.sizeDelta = new Vector2(pixelCellWidth, pixelCellWidth);
             //cell anchor is bottom left corner of rectangle
             newCellTrans.anchoredPosition =
                 new Vector2((pixelOffsetFromLeft + ((vec.x - 1) * pixelCellWidth)),
                             pixelOffsetFromBottom + ((vec.y - 1) * pixelCellWidth));
             newCell.name = vec.ToString();
         }
     }
 }
Example #14
0
    void Start()
    {
        InvokeRepeating("ssss", 1, 1);
        //GameTimer.AwaitLoopSeconds(1, ssss).ForgetAwait();
        for (int col = 0; col < mapSize.x; col += 1)
        {
            for (int row = 0; row < mapSize.y; row += 1)
            {
                GameObject go  = GameObject.Instantiate <GameObject>(tilePrefab);
                Vector3    pos = go.transform.position;

                Vector2Int point       = new Vector2Int(col, row);
                Vector2    spacing     = Coords.GetSpacing(point);
                Vector2    offsetCoord = Coords.GetOffsetCoord_odd_r(point);
                go.name = point.ToString() + ":" + Coords.odd_r_to_cube(point).ToString() + ":" + Coords.cube_to_axial(Coords.odd_r_to_cube(point)).ToString();
                cellViewSet.Add(point, go.AddComponent <CellView>());
                pos.x = spacing.x + offsetCoord.x;
                pos.z = spacing.y + offsetCoord.y;
                pos.y = 0;
                go.transform.position = pos;
            }
        }
    }
Example #15
0
    private void LoadChunk(Vector2Int chunkPosition)
    {
        GameObject chunkObject = new GameObject();

        chunkObject.name = chunkPosition.ToString();

        // Set position and parent
        chunkObject.transform.SetParent(chunkContainer.transform);
        chunkObject.transform.position    = new Vector3((chunkPosition.x + 0.5f) * ChunkSize, 0, (chunkPosition.y + 0.5f) * ChunkSize);
        chunkObject.transform.localScale *= settings.scale;

        var meshFilter   = chunkObject.AddComponent <MeshFilter>();
        var meshCollider = chunkObject.AddComponent <MeshCollider>();
        var meshRenderer = chunkObject.AddComponent <MeshRenderer>();
        var chunk        = chunkObject.AddComponent <TerrainChunk>();

        meshRenderer.sharedMaterial = new Material(terrainMaterial);
        chunk.terrain         = this;
        chunk.generator       = generator;
        chunk.chunkCoordinate = chunkPosition;
        chunk.Setup();

        chunks.Add(chunkPosition, chunk);
    }
Example #16
0
    public void UpdatePlayerPosition(Vector2Int position)
    {
        if (position.x < 0 || position.x > mapSizeX || position.y < 0 || position.y > mapSizeY)
        {
            Debug.LogError("UpdatePlayerPosition: Invalid position: " + position.ToString());
        }
        playerPos = position;

        if (!IsBorder(position))
        {
            // Player is on the field
            AddToTrail(position);
        }
        else
        {
            if (trail.Count > 0)
            {
                // Player was on the field and now back to border

                // TODO: Close the area according to the enemies
            }
        }
        // SetTileAtPosition(position, TileType.Player);
    }
Example #17
0
    public void AddGameObject(GameObject go, ConstructionLayer.LayerType layer, bool objectIsBatchable, bool forceUpdate)
    {
        Vector2Int cell = MapChunk.WorldToCell(go.transform.position);

        // create new chunk if needed
        if (!grid.ContainsKey(cell))
        {
            GameObject chunkGo = new GameObject();
            chunkGo.name                    = "chunk " + cell.ToString();
            chunkGo.transform.parent        = chunkContainer;
            chunkGo.transform.position      = MapChunk.CellToWorld(cell);
            chunkGo.transform.localRotation = Quaternion.identity;
            chunkGo.transform.localScale    = Vector3.one;
            chunkGo.SetActive(true);

            MapChunk newchunk = chunkGo.AddComponent <MapChunk>();
            newchunk.InitContainers();
            grid.Add(cell, newchunk);
        }

        // add object and schedule batching job if needed
        MapChunk chunk = grid[cell];

        chunk.AddGameObject(go, (int)layer, objectIsBatchable);
        if (forceUpdate && chunk.batchUpdate.Count != 0)
        {
            foreach (Material m in chunk.batchUpdate)
            {
                JobGrid job = new JobGrid();
                job.jobType   = JobType.Rebake;
                job.chunkCell = cell;
                job.material  = m;
                jobs.Enqueue(job);
            }
        }
    }
Example #18
0
 public override string ToString()
 {
     return(value.ToString());
 }
Example #19
0
 public override string ToString()
 {
     return(position.ToString());
 }
Example #20
0
    private List <MapItem> MakeMapLayout()
    {
        var layout = new List <MapItem>();

        InitRandom();

        int brokenTrailsSoFar = 0;

        var loc = new Vector2Int(-size, 0);
        var dir = Vector2Int.right;

        layout.Add(CreateTrack(loc, dir));
        loc += dir;
        layout.Add(CreateTrack(loc, dir));
        loc += dir;

        int j = 0;

        while (j <= maxIterations)
        {
            j++;
            for (int i = 0; i < Random.Range(1, 12); i++)
            {
                // Stop and backtrack if placement invalid
                if (!CheckValidPlacementStraight(layout, loc))
                {
                    Debug.Log($"Will not place straight rail at {loc.ToString()} because of invalid placement.");
                    Backtrack(layout, ref loc, ref dir, 2);
                    break;
                }

                if (layout.Count > initialUnbrokenTrails && brokenTrailsSoFar < maxBrokenTrails && Random.value < brokenTrailChance)
                {
                    layout.Add(CreateBroken(loc, dir));
                    brokenTrailsSoFar += 1;
                }
                else
                {
                    layout.Add(CreateTrack(loc, dir));
                }
                loc += dir;

                // Stop if we're about to hit the edge
                if (loc.x > size || loc.x < -size || loc.y > size || loc.y < -size)
                {
                    Debug.Log($"Will not place straight rail at {loc.ToString()} because of the edge.");
                    Backtrack(layout, ref loc, ref dir, 2);
                    break;
                }
            }

            if (j < maxIterations)
            {
                if (!CheckValidPlacementTurn(layout, loc))
                {
                    Debug.Log($"Will not place curved rail at {loc.ToString()} because of invalid placement.");
                    Backtrack(layout, ref loc, ref dir, 2);
                }

                var prevDir = dir;
                if (Random.value < 0.5)
                {
                    dir.Set(dir.y, -dir.x);
                    layout.Add(CreateTurn(loc, GetRotation(dir) + CTurn, prevDir));
                }
                else
                {
                    dir.Set(-dir.y, dir.x);
                    layout.Add(CreateTurn(loc, GetRotation(dir), prevDir));
                }
                loc += dir;
            }
        }

        var item = layout[layout.Count - finishOffset];

        if (item.Type == MapItemType.Turn)
        {
            item = layout[layout.Count - finishOffset - 1];
        }
        layout.Add(CreateFinish(new Vector2Int(Mathf.RoundToInt(item.Location.x), Mathf.RoundToInt(item.Location.z)), item.PreviousDirection));

        return(layout);
    }
Example #21
0
    private int get_dijkstra(dijkstra_maps ref_map, Vector2Int t)
    {
        switch (ref_map)
        {
        case dijkstra_maps.enemy_location:
            return(util_ref.d_manager.enemy_location[t.x, t.y]);

        case dijkstra_maps.player_distance:
            return(util_ref.d_manager.player_distance[t.x, t.y]);

        case dijkstra_maps.player_sight:
            return(util_ref.d_manager.player_sight[t.x, t.y]);

        default:
            Debug.LogError("Get_Dijkstra returned -1 for map " + ref_map.ToString() + " and square " + t.ToString());
            return(-1);
        }
    }
Example #22
0
 private void SetActiveGridPosition(Grid grid, Vector2Int?gridPosition = null)
 {
     Debug.Log($"Selected grid position {gridPosition?.ToString()}");
     this.activeGridPosition = gridPosition;
     this.UpdatePanel(grid);
 }
Example #23
0
    // Flood fill tiles map
    public void Fill(Vector2Int position)
    {
        // tilemap.FloodFill(new Vector3Int(position.x, position.y, 0), tilesDict[TileType.Filled]);
        if (position.x <= 0 || position.x >= mapSizeX || position.y <= 0 || position.y >= mapSizeY)
        {
            Debug.LogError("FloodFill: Invalid position: " + position.ToString());
        }
        if (map[position.x, position.y] != TileType.Empty)
        {
            return;
        }

        // Define valid tile types we want to fill
        List <TileType> validTiles = new List <TileType> {
            TileType.Empty
        };

        // TileType curTileType = map[position.x, position.y];
        List <Vector2Int> queue = new List <Vector2Int>();

        queue.Add(position);
        while (queue.Count > 0)
        {
            int num_elements = queue.Count;
            for (int n = 0; n < num_elements; n++)
            {
                int y    = queue[n].y;
                int west = queue[n].x;
                int east = queue[n].x;
                while (validTiles.Contains(map[west, y]))
                {
                    west--;
                }
                west++;
                while (validTiles.Contains(map[east, y]))
                {
                    east++;
                }
                east--;
                for (int i = west; i <= east; i++)
                {
                    // Change tile
                    SetTileAtPosition(new Vector2Int(i, y), TileType.Filled);

                    // Check color above and below and add to queue
                    if (validTiles.Contains(map[i, y + 1]))
                    {
                        queue.Add(new Vector2Int(i, y + 1));
                    }
                    if (validTiles.Contains(map[i, y - 1]))
                    {
                        queue.Add(new Vector2Int(i, y - 1));
                    }
                }
            }
            // Remove all previous positions
            queue.RemoveRange(0, num_elements);
        }

        foreach (var t in trail)
        {
            SetTileAtPosition(t, TileType.Filled);
        }
        trail.Clear();
    }
Example #24
0
    // Update is called once per frame
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Vector2Int gridPoint = Geometry.GridFromPoint(hit.point);
            tileHighlight.SetActive(true);
            tileHighlight.transform.position = Geometry.PointFromGrid(gridPoint);

            if (Input.GetMouseButtonDown(0))
            {
                if (!moveLocations.Contains(gridPoint)) // Is not a valid move
                {
                    //return;
                    Debug.Log("Moving to " + gridPoint.ToString() + " is not logically possible");
                    ExitState(false);
                }
                else if (GameManager.instance.PieceAtGrid(gridPoint) == null)
                {
                    //GameManager.instance.AddMove(movingPiece, gridPoint, false);

                    //  find out if moving piece is King and check if it just castled
                    if (movingPiece.GetComponent <Piece>().type == PieceType.King)
                    {
                        if (movingPiece.GetComponent <King>().HasMoved == false)
                        {
                            if (gridPoint.x == 2)
                            {
                                GameManager.instance.Castling(gridPoint, true);
                            }
                            else if (gridPoint.x == 6)
                            {
                                GameManager.instance.Castling(gridPoint, false);
                            }
                        }
                    }
                    else if (movingPiece.GetComponent <Piece>().type == PieceType.Pawn)
                    {
                        GameManager.instance.Move(movingPiece, gridPoint);
                        // Checking for Pawn  En passe
                        if (Mathf.Abs(GameManager.instance.GridForPiece(movingPiece).y -
                                      gridPoint.y) == 1 && Math.Abs(GameManager.instance.GridForPiece(movingPiece).x - gridPoint.x) == 1)
                        {
                            if (GameManager.instance.GridForPiece(movingPiece).x > gridPoint.x)
                            {
                                GameManager.instance.CapturePieceAt(new Vector2Int(gridPoint.x, gridPoint.y - GameManager.instance.currentPlayer.forward));
                            }
                            else
                            {
                                GameManager.instance.CapturePieceAt(new Vector2Int(gridPoint.x, gridPoint.y - GameManager.instance.currentPlayer.forward));
                            }
                        }
                        HasPawnReachedTheOtherSide(gridPoint);
                    }
                    else
                    {
                        GameManager.instance.Move(movingPiece, gridPoint);
                    }
                }
                // Reference point 3: Handle Capturing an enemy piece at the grid point if any
                else
                {
                    //GameManager.instance.AddMove(movingPiece, gridPoint, true);
                    GameManager.instance.CapturePieceAt(gridPoint);
                    GameManager.instance.Move(movingPiece, gridPoint);
                    // Check for pawn upgradation
                    if (movingPiece.GetComponent <Piece>().type == PieceType.Pawn)
                    {
                        HasPawnReachedTheOtherSide(gridPoint);
                    }
                }


                if (GameManager.instance.IsKingInCheck(GameManager.instance.currentPlayer))    // Current Player's King is in check
                {
                    // Rewind the move OR Invalidate the current move
                }

                if (GameManager.instance.IsKingInCheck(GameManager.instance.otherPlayer))   // Opponents King is in check
                {
                    Debug.Log("King is in check");
                }

                ExitState(true);
            }
        }
        else
        {
            tileHighlight.SetActive(false);
        }
    }
Example #25
0
 public static string ToStringOrDefault(this Vector2Int self, string toDefaultString = null,
                                        Vector2Int defaultValue = default)
 {
     return(ObjectUtil.Equals(self, defaultValue) ? toDefaultString : self.ToString());
 }
Example #26
0
 public static string Path(Vector2Int point)
 {
     return(Path() + "/" + point.ToString() + ".asset");
 }
Example #27
0
    public Mesh GenMesh(Vector2 unit_size, GameObject plane)
    {
        Vector2 total_size = new Vector2(0f, 0f);

        total_size.x = plane.transform.lossyScale.x * CommonData.UnitSize;
        total_size.y = plane.transform.lossyScale.z * CommonData.UnitSize;

        Vector2Int     total_num    = new Vector2Int(Mathf.CeilToInt(total_size.x / unit_size.x), Mathf.CeilToInt(total_size.y / unit_size.y));
        Mesh           tmplate_mesh = new Mesh();
        List <Vector3> vertices     = new List <Vector3>();
        List <Vector2> uv           = new List <Vector2>();
        List <Vector3> normals      = new List <Vector3>();
        List <int>     indices      = new List <int>();
        Vector2Int     index        = Vector2Int.zero;
        Vector3        scale        = plane.transform.lossyScale;

        //锚点设置到中间
        total_num /= 2;
        for (int i = -total_num.x; i <= total_num.x; ++i, ++index.x)
        {
            index.y = 0;
            for (int j = -total_num.y; j <= total_num.y; ++j, ++index.y)
            {
                Vector2 offset = new Vector2(i, j) * unit_size;
                vertices.Add(new Vector3(offset.x / scale.x, 0, offset.y / scale.z));
                uv.Add(new Vector2(index.x * 0.5f / total_num.x, index.y * 0.5f / total_num.y));
                normals.Add(new Vector3(0, 1, 0));
                Debug.Log("[GenTemplateMesh Vertex] index : " + offset.ToString() + " : " + vertices.ToArray()[vertices.Count - 1].ToString());
                //设置三角形索引序列,顺时针生成
                //每个定点对应左边的一个倒三角跟右边的一个正三角
                if (total_num.y == j)
                {
                    continue;
                }
                if (-total_num.x != i)
                {
                    int index_0 = index.y * (2 * total_num.x + 1) + index.x;
                    int index_2 = (index.y + 1) * (2 * total_num.x + 1) + index.x - 1;
                    int index_1 = (index.y + 1) * (2 * total_num.x + 1) + index.x;
                    indices.Add(index_0);
                    indices.Add(index_1);
                    indices.Add(index_2);
                    Debug.Log("[GenTemplateMesh] index :" + index.ToString() + "  " + index_0.ToString() + " " + index_1.ToString() + " " + index_2.ToString());
                }
                if (total_num.x != i)
                {
                    int index_0 = index.y * (2 * total_num.x + 1) + index.x;
                    int index_2 = (index.y + 1) * (2 * total_num.x + 1) + index.x;
                    int index_1 = index_0 + 1;
                    indices.Add(index_0);
                    indices.Add(index_1);
                    indices.Add(index_2);
                    Debug.Log("[GenTemplateMesh] index :" + index.ToString() + "  " + index_0.ToString() + " " + index_1.ToString() + " " + index_2.ToString());
                }
            }
        }

        tmplate_mesh.SetVertices(vertices);
        tmplate_mesh.SetUVs(0, uv);
        tmplate_mesh.SetNormals(normals);
        tmplate_mesh.SetIndices(indices, MeshTopology.Triangles, 0);
        tmplate_mesh.RecalculateBounds();
        Debug.Log("[GenMesh] vertices count : " + vertices.Count.ToString() + " indices count : " + indices.Count.ToString() + " uvs count : " + uv.Count.ToString() + " normals count : " + normals.Count.ToString());
        return(tmplate_mesh);
    }
Example #28
0
    // Start is called before the first frame update
    void Start()
    {
        _controller      = GetComponent <FlagController>();
        _spawnController = GetComponent <SpawnController>();

        //Grid init
        RoomGrid = new Room[gridWidthHeight, gridWidthHeight];

        roomsToGen = roomGenNumber;

        startingGridPostion = new Vector2Int(gridWidthHeight / 2, gridWidthHeight / 2);
        Debug.Log("Starting grid location " + startingGridPostion.ToString());

        deltaVectors    = _controller.deltaVectors;
        directionsDelta = _controller.directionsDelta;

        //Create main room on grid
        var homeRoom = SetupMainRoom();

        var playerGameObject = GameObject.FindWithTag("Player");

        if (playerGameObject == null)
        {
            playerGameObject = _spawnController.SpawnPlayerInRoomCenter(homeRoom);
        }
        else
        {
            SpawnController.MoveObjectToRoomCenter(playerGameObject, homeRoom);
        }

        //We get the modifier that we have to multiply delta movement by because of how Tiler scales things
        modifier = _gridGameObject.GetComponent <Grid>().cellSize;

        //Loading all the saved room prefabs
        var _roomGameObjects = LoadGameObjectRooms();

        GameObjectRoomsByExits = SortGameObjectRoomsBySize(_roomGameObjects);

        var actionList = new[]
        {
            new Action(() =>
            {
                GenerateRoomsNew(startingGridPostion.x + deltaVectors[0].x,
                                 startingGridPostion.y + deltaVectors[0].y, directionsDelta[0], homeRoom, branchMaxLength);
            }),
            new Action(() =>
            {
                GenerateRoomsNew(startingGridPostion.x + deltaVectors[1].x,
                                 startingGridPostion.y + deltaVectors[1].y, directionsDelta[1], homeRoom, branchMaxLength);
            }),
            new Action(() =>
            {
                GenerateRoomsNew(startingGridPostion.x + deltaVectors[2].x,
                                 startingGridPostion.y + deltaVectors[2].y, directionsDelta[2], homeRoom, branchMaxLength);
            }),
            new Action(() =>
            {
                GenerateRoomsNew(startingGridPostion.x + deltaVectors[3].x,
                                 startingGridPostion.y + deltaVectors[3].y, directionsDelta[3], homeRoom, branchMaxLength);
            })
        }.ToList();

        Shuffle(actionList);
        for (int i = 0; i < actionList.Count; i++)
        {
            var action = actionList[i];
            action();
        }

        PatchLeftovers();

        /**
         * //Pretty print
         * int rowLength = RoomGrid.GetLength(0);
         * int colLength = RoomGrid.GetLength(1);
         * string arrayString = "";
         * for (int i = 0; i < rowLength; i++)
         * {
         *  for (int j = 0; j < colLength; j++)
         *  {
         *      arrayString += string.Format("{0} ", RoomGrid[i, j] == null ? "None" : RoomGrid[i,j].roomGameObject.name);
         *      arrayString += "     ";
         *  }
         *  arrayString += Environment.NewLine + Environment.NewLine;
         * }
         **/

        AddNavMeshModifierToWalls();
        AddNavMeshModifierToPillars();
        AddTagToEveryRoomWall();
        AddTagToEveryRoomPillar();
        BakeNavMesh();

        gameObject.GetComponent <SpawnController>().Initialize();
        gameObject.GetComponent <SpawnController>().SpawnForAllRooms();

        if (!gameObject.GetComponent <SpawnController>().bossSpawned)
        {
            var spawnController = gameObject.GetComponent <SpawnController>();

            foreach (var room in spawnController.roomGrid)
            {
                if (room != null)
                {
                    spawnController.ForceSpawnBoss(room.GridPosition);
                    Debug.LogWarning("Force spawned");
                    break;
                }
            }
        }

        gameObject.GetComponent <LocationController>()
        .Initialize(startingGridPostion, RoomGrid, playerGameObject, gameObject.GetComponent <SpawnController>());

        gameObject.GetComponent <KillQuestController>().Init();

        RemoveFlagRendering();


        _roomGameObjects.ForEach(room => Destroy(room));
        Debug.Assert(madeBossRoom);
    }
 private void UpdateObjName()
 {
     transform.parent.name = coordinates.ToString();
 }
Example #30
0
 public override string ToString()
 {
     return("Position: " + position.ToString() + " Doors: u" + upDoor + " d" + downDoor + " l" + leftDoor + " r" + rightDoor + "Boss: " + boss);
 }