示例#1
0
    void ExecuteMove(Tile3D startTile, Tile3D endTile)
    {
        if (endTile.currentPiece != null && endTile.currentPiece.type == ChessPiece.Type.KING)
        {
            if (board.currentMove == ChessPiece.Team.WHITE)
            {
                turnText.text = "White wins!!";
            }
            else
            {
                turnText.text = "Black wins!!";
            }
            StartCoroutine(LoadStartScene());
        }

        Point4 startPosition = new Point4(startTile.x, startTile.y, startTile.z, startTile.w);
        Point4 newPosition   = new Point4(endTile.x, endTile.y, endTile.z, endTile.w);

        board.MovePiece(board.GetMove(startPosition, newPosition));


        if (board.currentMove == ChessPiece.Team.BLACK)
        {
            turnText.text = "Black's turn";
        }
        else if (board.currentMove == ChessPiece.Team.WHITE)
        {
            turnText.text = "White's turn";
        }

        attackers.ComputeAttackers();
    }
示例#2
0
    void LateUpdate()
    {
        if (Input.GetMouseButtonUp(0) && start != null)
        {
            Tile3D tile = start.transform.GetComponent <Tile3D>();
            if (tile == null)
            {
                // touchedTile = null;
            }
            else
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

                if (Physics.Raycast(ray.origin, ray.direction, out raycastHit, Mathf.Infinity, layerForDetectTiles))
                {
                    end = raycastHit.transform.gameObject;

                    if (start.transform.position == end.transform.position)
                    {
                        touchedTile = tile;
                        grid.SelectTile(touchedTile.node);
                    }
                }
            }
        }
    }
示例#3
0
    //=====================================================
    private void OnEnable()
    {
        foreach (Transform child in transform)
        {
            if (child.GetComponent <Tile3D>() != null)
            {
                thirdMeshBuilder = child.GetComponent <Tile3D>();
            }

            if (child.GetComponent <SecondMeshCreator>() != null)
            {
                secondMeshBuilder = child.GetComponent <SecondMeshCreator>();
            }
        }

        if (thirdMeshBuilder == null)
        {
            GameObject obj = new GameObject("ThirdMesh");
            thirdMeshBuilder     = obj.AddComponent <Tile3D>();
            obj.transform.parent = transform;
        }
        if (secondMeshBuilder == null)
        {
            GameObject obj = new GameObject("SecondMesh");
            secondMeshBuilder    = obj.AddComponent <SecondMeshCreator>();
            obj.transform.parent = transform;
        }


        Debug.Log("SB_OnEnable");
    }
示例#4
0
    void UpdateUVs(Tile tile, Tile3D t3, float w, float h, int rot)
    {
        var r = t3.rect;

        rotUVs[0] = new Vector2(r.xMin / w, r.yMin / h);
        rotUVs[1] = new Vector2(r.xMax / w, r.yMin / h);
        rotUVs[2] = new Vector2(r.xMax / w, r.yMax / h);
        rotUVs[3] = new Vector2(r.xMin / w, r.yMax / h);
        UpdateUVs(subdivisions, rotUVs[rot % 4], rotUVs[(rot + 1) % 4], rotUVs[(rot + 2) % 4], rotUVs[(rot + 3) % 4]);
    }
示例#5
0
 /// <summary>
 /// Used to draw a GUI text representing tile hight when the 3D preview
 /// is generated
 /// </summary>
 void OnGUI()
 {
     if (rot == -90 || (rot == 0 && index == 0))
     {//The second condition is a special case for the last tile.
      //Otherwise OnGUI won't work and height is not displayed
         if (current != null)
         {
             currentTile = current.GetComponent <Tile3D>();
             GUI.TextField(new Rect(2, 2, 35, 20), currentTile.height.ToString("F2"));
         }
     }
 }
示例#6
0
    public bool RaycastTile(Ray ray, float maxDistance, out RaycastHit hit, out Tile3D tile)
    {
        var coll = GetComponent <MeshCollider>();

        if (coll.Raycast(ray, out hit, maxDistance))
        {
            tile = GetSurface(hit.point, hit.normal);
            return(true);
        }
        tile = null;
        return(false);
    }
示例#7
0
    //-----------------------------------------------------
    //
    //-----------------------------------------------------
    void OnGUI()
    {
        using (new EditorGUILayout.HorizontalScope())
        {
            stageData = (StageData)EditorGUILayout.ObjectField("StageData", stageData, typeof(StageData), true);
            if (GUILayout.Button("New", GUILayout.Width(50)))
            {
                Debug.Log("ここから過程大事に");
            }
        }

        EditorGUILayout.Space();

        EditorGUI.BeginChangeCheck();
        {
            toolType = (ToolType)GUILayout.Toolbar((int)toolType, new string[] { "Tile3D", "Stage" }, (GUIStyle)"OL Titlemid");
        }
        if (EditorGUI.EndChangeCheck())
        {
            if (toolType == ToolType.Tile3D)
            {
                if (tiler == null)
                {
                    tiler = FindObjectOfType <Tile3D>();
                }
                Selection.activeGameObject = tiler.gameObject;

                Debug.Log("AB");
            }
            else
            if (toolType == ToolType.Stage)
            {
                if (builder == null)
                {
                    builder = FindObjectOfType <StageBuilder>();
                }
                Selection.activeGameObject = builder.gameObject;

                Debug.Log("CD");
            }
        }

        if (toolType == ToolType.Tile3D)
        {
            tileTool = (Tile3DTool)GUILayout.Toolbar((int)tileTool, new string[] { "Mesh", "Paint" }, (GUIStyle)"OL Titlemid");
        }
        else
        if (toolType == ToolType.Stage)
        {
            stageTool = (StageTool)GUILayout.Toolbar((int)stageTool, new string[] { "Data", "Gimick", "Respawn", "Right", "Left" }, (GUIStyle)"OL Titlemid");
        }
    }
示例#8
0
    void ClickOffTile()
    {
        if (selectedTile != null && destinationTile == null)
        {
            selectedTile = null;
        }
        else if (selectedTile != null && destinationTile != null)
        {
            destinationTile = null;
        }

        UpdateTileHighlights();
    }
示例#9
0
    void OnEnable()
    {
        SceneView.onSceneGUIDelegate -= OnSceneGUI;
        SceneView.onSceneGUIDelegate += OnSceneGUI;

        Undo.undoRedoPerformed -= OnUndoRedo;
        Undo.undoRedoPerformed += OnUndoRedo;

        LoadTiles();
        if (selectedTile == null && tiles.Length > 0)
        {
            selectedTile = tiles[0];
        }
    }
示例#10
0
    public override bool StartUp(Vector3Int position, ITilemap tilemap, GameObject go)
    {
        bool result = base.StartUp(position, tilemap, go);

        if (go)
        {
            Tile3D tile3D = go.GetComponent <Tile3D>();
            if (tile3D)
            {
                tile3D.spriteRenderer.sprite = this.sprite;
            }
            go.transform.localEulerAngles = new Vector3(0, 0, 0);
            go.transform.localScale       = Vector3.one;
        }
        return(true);
    }
示例#11
0
    public void InitMap(int rows, int cols)
    {
        if (rows <= 0 || cols <= 0)
        {
            return;
        }

        tiles = new Tile3D[rows, cols];
        for (int i = 0; i < tiles.GetLength(0); i++)
        {
            for (int j = 0; j < tiles.GetLength(1); j++)
            {
                tiles[i, j] = new Tile3D(0, i, j);
            }
        }
    }
示例#12
0
    /// <summary>
    /// TODO: Function under construction
    /// </summary>
    /// <param name="tileID">Tile I.</param>
    /// <param name="map">Map.</param>
    /// <param name="tileObject">Tile object.</param>
    private void AttachTileProperties(int tileID, TiledMap map, GameObject tileObject)
    {
        for (int i = 0; i < map.tileSets.Length; i++)
        {
            TiledTileSetFile tSet = map.tileSets[i];
            if (tSet.image == null)
            {
                //for single images
                foreach (TiledTile tile in tSet.tiles)
                {
                    if (tile.id + map.tileSetEntries[i].firstGID == tileID)
                    {
                        if (tile.customProperties != null && tile.customProperties.Length > 0)
                        {
                            Tile3D tileScript = tileObject.AddComponent <Tile3D>();
                            for (int j = 0; j < tile.customProperties.Length; j++)
                            {
                                string pName  = tile.customProperties[j].name.ToLower();
                                string pValue = tile.customProperties[j].value;

                                if (pName.Equals("generatecollider"))
                                {
                                    bool gen;
                                    if (bool.TryParse(pValue, out gen))
                                    {
                                        tileScript.generateCollider = gen;
                                    }
                                }
                                else if (pName.Equals("minrandomdisplacement") || pName.Equals("maxrandomdisplacement"))
                                {
                                    /*
                                     * float x, y, z;
                                     * Vector3 displacement;
                                     * string[] vals = pValue.Split(',');
                                     * if (vals.Length == 3)
                                     * {
                                     *  //TODO: continue from here
                                     * }
                                     */
                                }
                            }
                        }
                    }
                }
            }
        }
    }
示例#13
0
    void ClickTile(Tile3D tile)
    {
        warningText.text = "";
        if (tile == selectedTile)
        {
            return;
        }

        if (selectedTile == null)
        {
            selectedTile = tile;
        }
        if (selectedTile != null && tile == destinationTile)
        {
            //Move piece
            ExecuteMove(selectedTile, destinationTile);

            selectedTile    = null;
            destinationTile = null;
        }
        else if (selectedTile != null && selectedTile.currentPiece != null && destinationTile == null)
        {
            if (selectedTile.currentPiece.team == board.currentMove &&
                selectedTile.currentPiece.IsValidMove(new Point4(tile.x, tile.y, tile.z, tile.w)))
            {
                destinationTile = tile;
            }
            else
            {
                selectedTile = tile;
            }
        }
        else if (selectedTile != null && selectedTile.currentPiece == null && destinationTile == null)
        {
            selectedTile = tile;
        }
        else if (selectedTile != null && selectedTile.currentPiece != null && destinationTile != null && tile != destinationTile)
        {
            destinationTile = null;
        }

        UpdateTileHighlights();
    }
示例#14
0
    // public override void OnInspectorGUI()
    // {
    //     tile3D = target as Tile3D;

    //     EditorGUILayout.BeginVertical();
    //     {
    //         serializedObject.Update();

    //         GUI.enabled = false;
    //         EditorGUILayout.ObjectField("Script", MonoScript.FromMonoBehaviour((Tile3D)target), typeof(Tile3D), false);
    //         GUI.enabled = true;
    //     }
    //     EditorGUILayout.EndVertical();
    // }

    protected virtual void OnSceneGUI()
    {
        tile3D = target as Tile3D;

        Handles.Label(tile3D.transform.position + (Vector3.forward / 2) + (Vector3.right / 4), string.Format("{0},{1}", tile3D.transform.position.x, tile3D.transform.position.z));

        Handles.BeginGUI();
        {
            GUILayout.BeginVertical();
            {
                GUILayout.BeginArea(new Rect(260, 20, 100, 500));
                {
                }
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(140, 20, 100, 500));
                {
                    var start = GameObject.FindGameObjectWithTag("start");
                    if (start == null)
                    {
                        start = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        start.GetComponent <MeshRenderer>().enabled = false;
                        start.name = "Start";
                        start.tag  = "start";
                    }
                }
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(20, 20, 100, 500));
                {
                }
                GUILayout.EndArea();
            }
            GUILayout.EndVertical();
        }
        Handles.EndGUI();

        if (GUI.changed && !Application.isPlaying)
        {
            EditorUtility.SetDirty(target);
        }
    }
示例#15
0
    void AddVerts(Tile tile, Tile3D t3, float w, float h, int rot, Vector3 nor,
                  float x0, float y0, float z0,
                  float x1, float y1, float z1,
                  float x2, float y2, float z2,
                  float x3, float y3, float z3,
                  int i0, int i1, int i2,
                  int i3, int i4, int i5)
    {
        var p = tile.pos;

        if (t3 != null)
        {
            int i = rendVerts.Count;
            rendVerts.Add(new Vector3(p.x + x0, p.y + y0, p.z + z0));
            rendVerts.Add(new Vector3(p.x + x1, p.y + y1, p.z + z1));
            rendVerts.Add(new Vector3(p.x + x2, p.y + y2, p.z + z2));
            rendVerts.Add(new Vector3(p.x + x3, p.y + y3, p.z + z3));
            var r = t3.rect;

            rotUVs[0] = new Vector2(r.xMin / w, r.yMin / h);
            rotUVs[1] = new Vector2(r.xMax / w, r.yMin / h);
            rotUVs[2] = new Vector2(r.xMax / w, r.yMax / h);
            rotUVs[3] = new Vector2(r.xMin / w, r.yMax / h);
            for (int j = 0; j < 4; ++j)
            {
                rendUVs.Add(rotUVs[(j + rot) % 4]);
            }

            rendTris.Add(i + i0); rendTris.Add(i + i1); rendTris.Add(i + i2);
            rendTris.Add(i + i3); rendTris.Add(i + i4); rendTris.Add(i + i5);
        }
        {
            int i = collVerts.Count;
            collVerts.Add(new Vector3(p.x + x0, p.y + y0, p.z + z0));
            collVerts.Add(new Vector3(p.x + x1, p.y + y1, p.z + z1));
            collVerts.Add(new Vector3(p.x + x2, p.y + y2, p.z + z2));
            collVerts.Add(new Vector3(p.x + x3, p.y + y3, p.z + z3));
            collTris.Add(i + i0); collTris.Add(i + i1); collTris.Add(i + i2);
            collTris.Add(i + i3); collTris.Add(i + i4); collTris.Add(i + i5);
        }
    }
示例#16
0
    public void PaintTile(Vector3Int pos, Vector3Int nor, Tile3D surface, int rot)
    {
        var tile = GetTile(pos);

        if (tile == null)
        {
            return;
        }
        if (nor.x > 0)
        {
            tile.right    = surface;
            tile.rotRight = rot;
        }
        else if (nor.x < 0)
        {
            tile.left    = surface;
            tile.rotLeft = rot;
        }
        else if (nor.y > 0)
        {
            tile.top    = surface;
            tile.rotTop = rot;
        }
        else if (nor.y < 0)
        {
            tile.bottom    = surface;
            tile.rotBottom = rot;
        }
        else if (nor.z > 0)
        {
            tile.front    = surface;
            tile.rotFront = rot;
        }
        else if (nor.z < 0)
        {
            tile.back    = surface;
            tile.rotBack = rot;
        }
    }
示例#17
0
    public void GenerateTileObjects()
    {
        if (tilePrefabs.Count == 0)
        {
            Debug.LogWarning("[Tilemap3D] No tile prefabs assigned; cannot generate tile objects.");
            return;
        }

        for (int i = 0; i < tiles.GetLength(0); i++)
        {
            for (int j = 0; j < tiles.GetLength(1); j++)
            {
                Tile3D currentTile = tiles[i, j];

                if (currentTile.prefabId >= 0 && currentTile.prefabId < tilePrefabs.Count)
                {
                    Vector3    tilePos = GetTilePositionInWorldSpace(currentTile);
                    Quaternion tileRot = Quaternion.Euler(tileRotation);
                    //tileRot = tileRot * Quaternion.Euler(0f, 180f, 0f); //very temp until rotation properly implemented
                    currentTile.gameObject = Instantiate(tilePrefabs[currentTile.prefabId], tilePos, tileRot, transform); //tiles[i, j]
                }
            }
        }
    }
示例#18
0
    public Vector3 GetTilePositionInWorldSpace(Tile3D tile)
    {
        Vector3 pos = new Vector3(mapOffset.x + (tile.row * tileWidth), mapOffset.y, mapOffset.z + (tile.col * tileWidth));

        return(pos);
    }
示例#19
0
    /// <summary>
    /// Reads updated map data from tmx file through TMXImporter and rebuilds
    /// the scene using the data from the new map. Any objects that were modified
    /// in the editor are kept without changing
    /// </summary>
    private void RebuildModels()
    {
        for (int i = 0; i < rootTransform.childCount; i++)
        {
            Transform layer = rootTransform.GetChild(i);

            List <GameObject> models = new List <GameObject>();
            while (layer.childCount > 0)
            {
                for (int j = 0; j < layer.childCount; j++)
                {
                    Transform      child   = layer.GetChild(j);
                    SpriteRenderer sr      = child.GetComponent <SpriteRenderer>();
                    SpriteToModel  mapping = GetMapping(sr.sprite);

                    if (mapping == null)
                    {
                        mapping = new SpriteToModel();
                        int    firstDashIndex = sr.sprite.name.IndexOf('-');
                        string spriteName     = sr.sprite.name.Substring(firstDashIndex + 1);
                        string modelName      = spriteName.Substring(0, spriteName.Length - 4);

                        for (int a = 0; a < modelsAtlases.Count; a++)
                        {
                            for (int k = 0; k < modelsAtlases[a].childCount; k++)
                            {
                                if (modelsAtlases[a].GetChild(k).name.Equals(modelName))
                                {
                                    mapping.model = modelsAtlases[a].GetChild(k).gameObject;
                                    break;
                                }
                            }
                        }

                        if (mapping.model == null)
                        {
                            mapping = null;
                        }
                        else
                        {
                            mapping.sprite        = sr.sprite;
                            mapping.modelRotation = float.Parse(
                                spriteName.Substring(spriteName.LastIndexOf('_') + 1, 3));

                            mappings.Add(mapping);
                        }
                    }

                    if (mapping != null)
                    {
                        Vector3 pos = new Vector3(child.position.x, 0.0f, child.position.y);

                        GameObject model = null;

                        if (model == null)
                        {
                            model      = (GameObject)GameObject.Instantiate(mapping.model);
                            model.name = mapping.sprite.name + ":" + layer.name + ":" + child.name;

                            model.isStatic           = true;
                            model.transform.position = pos;

                            model.transform.localScale = tileScale;

                            model.transform.Rotate(0, mapping.modelRotation, 0);
                            Tile3D tileScript = model.GetComponent <Tile3D>();
                            if (tileScript.generateCollider)
                            {
                                model.AddComponent <MeshCollider>();
                            }
                            ProcessRandomModifications(tileScript);

                            //TODO: needs fixing
                            // if(sr.transform.eulerAngles.z != 0)
                            // {
                            //     model.transform.Rotate(0, sr.transform.eulerAngles.z, 0);
                            //     Vector3 scale = model.transform.localScale;
                            //     scale.z *= -1;
                            //     model.transform.localScale = scale;
                            // }

                            // model.transform.localScale = new Vector3(
                            //    model.transform.localScale.x * (sr.flipX ? -1 : 1),
                            //    model.transform.localScale.y,
                            //    model.transform.localScale.z * (sr.flipY ? -1 : 1)
                            //    );
                        }

                        models.Add(model);
                    }
                    else
                    {
                        Debug.LogWarning("No 3D mapping found for '" + sr.sprite.name + "'. Cannot build 3D tile");
                    }
                    GameObject.DestroyImmediate(child.gameObject);
                }
            }

            foreach (GameObject model in models)
            {
                model.transform.parent = layer;
            }
        }
    }
示例#20
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        var targ = (Tile3D)target;

        //EditorGUILayout.LabelField("ID", targ.id.ToString());

        var r = targ.rect;

        EditorGUILayout.LabelField("Rect", r.x + ", " + r.y + ", " + r.width + ", " + r.height);

        if (GUILayout.Button("Pack Tiles"))
        {
            //Load all the tiles
            var guids = AssetDatabase.FindAssets("t:Tile3D");
            var tiles = new Tile3D[guids.Length];
            for (int i = 0; i < guids.Length; ++i)
            {
                var path = AssetDatabase.GUIDToAssetPath(guids[i]);
                tiles[i] = AssetDatabase.LoadAssetAtPath <Tile3D>(path);
            }
            //System.Array.Sort(tiles, (a, b) => a.id.CompareTo(b.id));

            //Get the required texture size
            int texWidth  = 16;
            int texHeight = 16;
            while (!ForEachTileRect(tiles, texWidth, texHeight, null))
            {
                texWidth *= 2;
                if (ForEachTileRect(tiles, texWidth, texHeight, null))
                {
                    break;
                }
                texHeight *= 2;
            }

            //Get the tiles texture
            var pixels = new Color32[texWidth * texHeight];

            //Pack the tiles into the atlas and paint the tileset texture
            ForEachTileRect(tiles, texWidth, texHeight, (t, x, y) =>
            {
                var tex        = t.texture;
                var tilePixels = tex.GetPixels32();
                for (int yy = 0; yy < tex.height + 2; ++yy)
                {
                    for (int xx = 0; xx < tex.width + 2; ++xx)
                    {
                        var col = GetPixel(tilePixels, tex.width, tex.height, xx - 1, yy - 1);
                        pixels[(y + yy) * texWidth + x + xx] = col;
                    }
                }
                t.rect = new Rect(x + 1, y + 1, tex.width, tex.height);
            });

            //Set the texture pixels
            var texture = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/TileEditor3D/Assets/Tiles.png");
            texture.Resize(texWidth, texHeight);
            texture.SetPixels32(pixels);
            texture.Apply();

            //Overwrite the texture PNG
            var texBytes = texture.EncodeToPNG();
            var texPath  = AssetDatabase.GetAssetPath(texture);
            System.IO.File.WriteAllBytes(texPath, texBytes);

            //Update the assets
            AssetDatabase.ImportAsset(texPath);
            AssetDatabase.SaveAssets();

            //Update UVs of all live tilemaps
            foreach (var tilemap in FindObjectsOfType <Tilemap3D>())
            {
                tilemap.UpdateUVs();
            }
        }
    }
示例#21
0
    /// <summary>
    /// Recalculates the center point of the models based on
    /// their settings in the attached Tile3D script and its geometry
    /// </summary>
    private bool FixPivots()
    {
        List <Transform> newParents   = new List <Transform>();
        List <Transform> newChildren  = new List <Transform>();
        List <Transform> processLater = new List <Transform>();

        for (int child = 0; child < transform.childCount; child++)
        {
            Transform  meshTransform = transform.GetChild(child);
            MeshFilter filter        = meshTransform.GetComponent <MeshFilter>();

            if (filter != null)
            {
                GameObject emptyParent = new GameObject();
                emptyParent.transform.position = meshTransform.position;

                emptyParent.name = meshTransform.name;
                if (meshTransform == sizeReference)
                {
                    sizeReference = emptyParent.transform;
                }

                Tile3D oldScript = meshTransform.GetComponent <Tile3D>();
                Tile3D newScript = emptyParent.AddComponent <Tile3D>();
                if (oldScript != null)
                {
                    newScript.alignTo = oldScript.alignTo;
                    DestroyImmediate(oldScript);
                }
                newChildren.Add(meshTransform);
                newParents.Add(emptyParent.transform);
            }
            else if (meshTransform.GetComponent <Tile3D>() == null)
            {
                processLater.Add(meshTransform);
            }
        }

        foreach (Transform child in processLater)
        {
            GameObject emptyParent = new GameObject();
            emptyParent.transform.position = child.position;
            if (child == sizeReference)
            {
                sizeReference = emptyParent.transform;
            }
            emptyParent.transform.parent = transform;
            emptyParent.name             = child.name;
            while (child.childCount != 0)
            {
                child.GetChild(0).parent = emptyParent.transform;
            }
        }

        foreach (Transform child in processLater)
        {
            DestroyImmediate(child.gameObject);
        }

        if (newParents.Count > 0)
        {
            for (int i = 0; i < newParents.Count; i++)
            {
                newChildren[i].parent = newParents[i];
                newParents[i].parent  = transform;
            }

            return(true);
        }

        Dictionary <int, Vector3[]> borders   = new Dictionary <int, Vector3[]>();
        Dictionary <int, Vector3[]> allShifts = new Dictionary <int, Vector3[]>();

        for (int child = 0; child < transform.childCount; child++)
        {
            float minX = float.MaxValue, minZ = float.MaxValue, minY = float.MaxValue;
            float maxX = float.MinValue, maxZ = float.MinValue, maxY = float.MinValue;

            Transform parentTransform = transform.GetChild(child);
            parentTransform.localScale = Vector3.one;
            Transform childTransform;

            Tile3D tileScript         = parentTransform.GetComponent <Tile3D>();

            if (tileScript == null)
            {
                tileScript = parentTransform.gameObject.AddComponent <Tile3D>();
            }

            Vector3[] shifts     = new Vector3[parentTransform.childCount];
            Vector3   shiftPivot = Vector3.zero;
            for (int i = 0; i < parentTransform.childCount; i++)
            {
                childTransform = parentTransform.GetChild(i);
                Collider col = childTransform.GetComponent <Collider>();

                if (i == 0)
                {
                    shifts[i]  = Vector3.zero;
                    shiftPivot = childTransform.localPosition;
                }
                else
                {
                    shifts[i] = childTransform.localPosition - shiftPivot;
                }

                childTransform.localPosition = Vector3.zero;

                if (col == null)
                {
                    if (tileScript.generateCollider)
                    {
                        col = childTransform.gameObject.AddComponent <MeshCollider>();
                    }
                }
                else
                {
                    if (!tileScript.generateCollider)
                    {
                        DestroyImmediate(col);
                    }
                }

                MeshFilter filter = childTransform.GetComponent <MeshFilter>();

                if (filter != null)
                {
                    Mesh    mesh = filter.sharedMesh;
                    Vector3 min  = shifts[i] + new Vector3(
                        mesh.bounds.min.x * childTransform.localScale.x,
                        mesh.bounds.min.y * childTransform.localScale.y,
                        mesh.bounds.min.z * childTransform.localScale.z
                        );
                    Vector3 max = shifts[i] + new Vector3(
                        mesh.bounds.max.x * childTransform.localScale.x,
                        mesh.bounds.max.y * childTransform.localScale.y,
                        mesh.bounds.max.z * childTransform.localScale.z
                        );
                    if (max.x > maxX)
                    {
                        maxX = max.x;
                    }
                    if (min.x < minX)
                    {
                        minX = min.x;
                    }
                    if (max.y > maxY)
                    {
                        maxY = max.y;
                    }
                    if (min.y < minY)
                    {
                        minY = min.y;
                    }
                    if (max.z > maxZ)
                    {
                        maxZ = max.z;
                    }
                    if (min.z < minZ)
                    {
                        minZ = min.z;
                    }
                }
            }

            float dx = maxX - minX;
            float dy = maxY - minY;
            float dz = maxZ - minZ;

            tileScript.height = dy;

            if (parentTransform == sizeReference)
            {
                if (dx > dz)
                {
                    maxDiff = dx;
                }
                else
                {
                    maxDiff = dz;
                }
            }

            Vector3 shapeCenter =
                new Vector3(
                    minX + (maxX - minX) * 0.5f,
                    minY,
                    minZ + (maxZ - minZ) * 0.5f
                    );
            borders.Add(child, new Vector3[] {
                new Vector3(minX, minY, minZ),
                new Vector3(maxX, maxY, maxZ),
                shapeCenter
            });

            allShifts.Add(child, shifts);
        }

        for (int child = 0; child < transform.childCount; child++)
        {
            Transform parentTransform = transform.GetChild(child);
            Vector3   min             = borders[child][0];
            Vector3   max             = borders[child][1];
            Vector3   shapeCenter     = borders[child][2];
            Vector3[] shifts          = allShifts[child];
            Tile3D    tileScript      = parentTransform.GetComponent <Tile3D>();

            for (int i = 0; i < parentTransform.childCount; i++)
            {
                Transform trans = parentTransform.GetChild(i);
                trans.Translate(-shapeCenter);
                trans.Translate(shifts[i]);

                if (tileScript.alignTo == Alignment.left ||
                    tileScript.alignTo == Alignment.lowerLeft ||
                    tileScript.alignTo == Alignment.upperLeft)
                {
                    trans.Translate(-(maxDiff * 0.5f - (shapeCenter.x - min.x)), 0, 0);
                }
                else if (tileScript.alignTo == Alignment.right ||
                         tileScript.alignTo == Alignment.lowerRight ||
                         tileScript.alignTo == Alignment.upperRight)
                {
                    trans.Translate(maxDiff * 0.5f - (shapeCenter.x + max.x), 0, 0);
                }

                if (tileScript.alignTo == Alignment.top ||
                    tileScript.alignTo == Alignment.upperRight ||
                    tileScript.alignTo == Alignment.upperLeft)
                {
                    trans.Translate(0, 0, maxDiff * 0.5f + (shapeCenter.z + max.z));
                }
                else if (tileScript.alignTo == Alignment.bottom ||
                         tileScript.alignTo == Alignment.lowerRight ||
                         tileScript.alignTo == Alignment.lowerLeft)
                {
                    trans.Translate(0, 0, -(maxDiff * 0.5f - (shapeCenter.z - min.z)));
                }
            }
        }

        return(false);
    }
示例#22
0
    void OnGUI()
    {
        if (!canEdit)
        {
            EditorGUILayout.HelpBox("Editing disabled.", MessageType.Warning);
            return;
        }

        if (tilemap == null || !tilemap.gameObject.activeInHierarchy)
        {
            EditorGUILayout.HelpBox("Select a Tilemap3D to edit.", MessageType.Info);
            return;
        }

        var noneIcon  = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/Gizmos/TileNone Icon.png");
        var blockIcon = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/Gizmos/TileBlock Icon.png");
        var paintIcon = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/Gizmos/TilePaint Icon.png");

        EditorGUILayout.BeginHorizontal();
        GUI.enabled = editMode != EditMode.None;
        if (GUILayout.Button(new GUIContent(noneIcon)))
        {
            SetEditMode(EditMode.None);
        }
        GUI.enabled = editMode != EditMode.Block;
        if (GUILayout.Button(new GUIContent(blockIcon)))
        {
            SetEditMode(EditMode.Block);
        }
        GUI.enabled = editMode != EditMode.Paint;
        if (GUILayout.Button(new GUIContent(paintIcon)))
        {
            SetEditMode(EditMode.Paint);
        }
        GUI.enabled = true;
        EditorGUILayout.EndHorizontal();

        if (editMode != EditMode.None)
        {
            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                EditorGUILayout.HelpBox("Hold ⌘ to delete.", MessageType.Info, true);
            }
            else
            {
                EditorGUILayout.HelpBox("Hold CTRL to delete.", MessageType.Info, true);
            }
        }

        var drawGrid = EditorPrefs.GetBool("Tilemap3D_drawGrid", true);

        drawGrid = EditorGUILayout.Toggle("Draw Grid", drawGrid);
        EditorPrefs.SetBool("Tilemap3D_drawGrid", drawGrid);

        paintInvisible = EditorGUILayout.Toggle("Raycast Invisible", paintInvisible);

        if (editMode == EditMode.Block)
        {
            overwriteBlock = EditorGUILayout.Toggle("Overwrite", overwriteBlock);
        }

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("↻"))
        {
            rotation = (rotation + 1) % 4;
        }
        if (GUILayout.Button("↺"))
        {
            rotation = (rotation + 5) % 4;
        }
        EditorGUILayout.EndHorizontal();

        LoadTiles();

        var viewWidth = EditorGUIUtility.currentViewWidth - 10f;

        EditorGUILayout.Space();

        var searchRect = EditorGUILayout.GetControlRect(GUILayout.Width(viewWidth - 12f));
        var cancelRect = searchRect;

        cancelRect.x     = cancelRect.xMax;
        cancelRect.width = 10f;

        var searchStyle  = GUI.skin.GetStyle("ToolbarSeachTextField");
        var searchCancel = GUI.skin.GetStyle("ToolbarSeachCancelButton");
        var searchEnd    = GUI.skin.GetStyle("ToolbarSeachCancelButtonEmpty");

        search = EditorGUI.TextField(searchRect, search, searchStyle);
        if (GUI.Button(cancelRect, "", string.IsNullOrEmpty(search) ? searchEnd : searchCancel))
        {
            search = string.Empty;
            GUIUtility.keyboardControl = 0;
        }

        var tiles = new List <Tile3D>();

        if (!string.IsNullOrEmpty(search))
        {
            var split = search.Split(' ');
            for (int i = 0; i < split.Length; ++i)
            {
                split[i] = split[i].ToLower();
            }
            foreach (var tile in this.tiles)
            {
                var tileName = tile.name.ToLower();
                foreach (var part in split)
                {
                    if (tileName.Contains(part))
                    {
                        tiles.Add(tile);
                        break;
                    }
                }
            }
        }
        else
        {
            tiles.AddRange(this.tiles);
        }

        //Draw the tiles on a grid
        var slotSize = 32f;
        var rect     = GUILayoutUtility.GetRect(viewWidth, slotSize);

        rect.x += 4f;
        var slot = new Rect(rect.x, rect.y, slotSize, slotSize);

        for (int i = 0; i < tiles.Count; ++i)
        {
            var tile = tiles[i];
            GUI.enabled = tile != selectedTile;

            GUI.matrix = Matrix4x4.identity;
            var btnRect = new Rect(slot.x + 1f, slot.y + 1f, slot.width - 2f, slot.height - 2f);
            if (GUI.Button(btnRect, string.Empty))
            {
                selectedTile = tile;
            }

            GUI.color = Color.white * (GUI.enabled ? 1f : 0.8f);
            var texRect = new Rect(btnRect.x + 2f, btnRect.y + 2f, btnRect.width - 4f, btnRect.height - 4f);

            if (rotation > 0)
            {
                GUIUtility.RotateAroundPivot(rotation * 90f, texRect.center);
            }

            GUI.DrawTexture(texRect, tile.texture);
            GUI.color = Color.white;

            slot.x += slotSize;
            if (slot.xMax > rect.xMax)
            {
                rect    = GUILayoutUtility.GetRect(viewWidth, slotSize);
                rect.x += 4f;
                slot    = new Rect(rect.x, rect.y, slotSize, slotSize);
            }
        }

        GUI.matrix = Matrix4x4.identity;

        if (tilemap != null)
        {
            Hotkeys();
        }
    }
示例#23
0
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            RaycastHit hit;
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                Transform objectHit = hit.transform;

                bool clickedTile = false;
                while (objectHit != null)
                {
                    if (objectHit.GetComponent <Tile3D>() != null)
                    {
                        ClickTile(objectHit.GetComponent <Tile3D>());
                        clickedTile = true;
                        break;
                    }
                    else
                    {
                        objectHit = objectHit.parent;
                    }
                }
                if (!clickedTile)
                {
                    ClickOffTile();
                }
            }
            else
            {
                ClickOffTile();
            }
        }

        if (Input.GetKey(KeyCode.Mouse1))
        {
            Tile3D     newAttackedTile = attackedTile;
            RaycastHit hit;
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                Transform objectHit = hit.transform;

                bool clickedTile = false;
                while (objectHit != null)
                {
                    if (objectHit.GetComponent <Tile3D>() != null)
                    {
                        newAttackedTile = objectHit.GetComponent <Tile3D>();
                        clickedTile     = true;
                        break;
                    }
                    else
                    {
                        objectHit = objectHit.parent;
                    }
                }
                if (!clickedTile)
                {
                    newAttackedTile = null;
                }
            }
            else
            {
                newAttackedTile = null;
            }

            if (newAttackedTile != attackedTile)
            {
                Debug.Log("Update " + attackedTile + " : " + newAttackedTile);
                attackedTile = newAttackedTile;
                UpdateTileHighlights();
            }
        }
        else
        {
            if (attackedTile != null)
            {
                attackedTile = null;
                UpdateTileHighlights();
            }
        }
    }
示例#24
0
    /// <summary>
    /// Updates by positioning the camera over the current model
    /// and capture a screenshot to be used as a 2D tile for that model.
    /// Another perspective camera is used to capture the screenshot for the
    /// 3D preview tile. This function also handles rotating all models once
    /// the current rotaion is completed for all of them. All tiles are captured
    /// as 3D preview in addition to top-view with 0, 90, 180 and 270 degrees rotations.
    /// File name format is height-tileObjectName_Rotation.png.
    /// When tile generation is done, the current object is saved as a prefab with collection
    /// name in "Assets/Prefabs" folder
    /// </summary>
    void Update()
    {
        if (transform.childCount == 0)
        {
            Debug.LogWarning("Warning: '" + gameObject.name + "' has no children to build tiles from. Exiting...");
            UnityEditor.EditorApplication.isPlaying = false;
            return;
        }

        if (prevCam == null)
        {
            return;
        }

        if (!GameViewUtils.SizeExists(GameViewSizeGroupType.Standalone, tileSize, tileSize))
        {
            GameViewUtils.AddCustomSize(GameViewUtils.GameViewSizeType.FixedResolution,
                                        GameViewSizeGroupType.Standalone, tileSize, tileSize,
                                        tileSize + "*" + tileSize + " tile generation");
        }

        GameViewUtils.SetSize(GameViewUtils.FindSize(GameViewSizeGroupType.Standalone, tileSize, tileSize));

        if (string.IsNullOrEmpty(collectionName.Trim()))
        {
            Debug.LogWarning("Warning: collection name cannot be empty. Exiting...");
            UnityEditor.EditorApplication.isPlaying = false;
            return;
        }

        string tilesPath = Application.dataPath + "/" + TILES_FOLDER + "/" + collectionName;

        if (rot > 270)
        {
            SetTextureAlpha();
            GenerateTilesetFile();
            Debug.Log("Done!! your sprites are in " + tilesPath);
            try
            {
                string atlasesFullPath = Application.dataPath + "/Resources/" + ATLASES_FOLDER;
                if (!Directory.Exists(atlasesFullPath))
                {
                    Directory.CreateDirectory(atlasesFullPath);
                }
                //Object prefab = PrefabUtility.CreateEmptyPrefab("Assets/Resources/" + ATLASES_FOLDER + "/" + collectionName + ".prefab");
                //PrefabUtility.ReplacePrefab(gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab);
                PrefabUtility.SaveAsPrefabAssetAndConnect(gameObject, "Assets/Resources/" + ATLASES_FOLDER + "/" + collectionName + ".prefab", InteractionMode.AutomatedAction);

                Debug.Log("Your tile collection was saved as " + atlasesFullPath + "/" + collectionName + ".prefab");
            }
            catch
            {
                Debug.LogError("Error: unable to save atlas prefab");
            }

            UnityEditor.EditorApplication.isPlaying        = false;
            EditorScriptsController.enableSpriteImporter2D = true;
            AssetDatabase.Refresh();
            EditorScriptsController.enableSpriteImporter2D = false;
            return;
        }

        MoveToNext();

        if (Time.frameCount < 5)
        {
            return;
        }

        string rotString = "_000";

        if (index == transform.childCount - 1)
        {
            //Special case of last tile
            if (rot == 0)
            {
                rotString = "_090";
            }
            else if (rot == 90)
            {
                rotString = "_180";
            }
            else if (rot == 180)
            {
                rotString = "_270";
            }
        }
        else
        {
            if (rot == 90)
            {
                rotString = "_090";
            }
            else if (rot == 180)
            {
                rotString = "_180";
            }
            else if (rot == 270)
            {
                rotString = "_270";
            }
        }

        currentTile = current.GetComponent <Tile3D>();

        string fullPath;

        if (rot != -90)
        {
            fullPath = tilesPath + "/" + currentTile.height.ToString("F2") + "-" + current.name + rotString + ".png";
        }
        else
        {
            fullPath = tilesPath + "/" + currentTile.height.ToString("F2") + "-" + current.name + "__PRV" + ".png";
        }
        generatedPaths.Add(fullPath);

        if (!Directory.Exists(tilesPath))
        {
            Directory.CreateDirectory(tilesPath);
        }

        try
        {
            ScreenCapture.CaptureScreenshot(fullPath);
        }
        catch
        {
            Debug.LogError("Error: unable to save 2D tile sprite '" + fullPath + "'. Exiting...");
            UnityEditor.EditorApplication.isPlaying = false;
        }

        index++;
        if (index == transform.childCount)
        {
            index = 0;
            rot  += 90;
            if (rot != 0)
            {
                for (int i = 0; i < transform.childCount; i++)
                {
                    Transform t = transform.GetChild(i);

                    t.Rotate(0, 90, 0, Space.World);
                }
            }
        }
    }
示例#25
0
    /// <summary>
    /// Reads properties stored in a Tile3D script and modifies
    /// the tile using the provided ranges of random modifications
    /// </summary>
    /// <param name="tile">Script to read randomization data from</param>
    private void ProcessRandomModifications(Tile3D tile)
    {
        if (tile.maxRandomCopies > 0 ||
            tile.randomRotationSnapAngle != 0.0f ||
            tile.maxRandomDisplacement != Vector3.zero ||
            tile.maxRandomScale != 0.0f)
        {
            GameObject midParent = new GameObject("Copy0");
            midParent.transform.parent   = tile.transform;
            midParent.transform.position = tile.transform.position;

            while (tile.transform.childCount > 1)
            {
                Transform originalChild = tile.transform.GetChild(0);
                if (originalChild == midParent.transform)
                {
                    originalChild = tile.transform.GetChild(1);
                }

                originalChild.transform.parent = midParent.transform;
            }

            for (int i = 0; i < tile.maxRandomCopies; i++)
            {
                GameObject newCopy = (GameObject)GameObject.Instantiate(midParent);
                newCopy.name                 = "Copy" + (i + 1);
                newCopy.transform.parent     = tile.transform;
                newCopy.transform.position   = midParent.transform.position;
                newCopy.transform.localScale = midParent.transform.localScale;
            }

            for (int i = 0; i < tile.maxRandomCopies + 1; i++)
            {
                Transform child = tile.transform.GetChild(i);

                float scaleFactor = Mathf.Clamp01(tile.maxRandomScale);

                float randomScale = Random.Range(-scaleFactor * 0.5f, scaleFactor * 0.5f);
                child.localScale += child.localScale * randomScale;

                if (tile.randomRotationSnapAngle > 0.0f)
                {
                    //for(int j = 0; j < child.childCount; j++){
                    int snap = Mathf.RoundToInt(tile.randomRotationSnapAngle * 0.5f);
                    if (snap == 0)
                    {
                        snap = 1;
                    }
                    int ang = Random.Range(0, 360);

                    while (ang % snap != 0)
                    {
                        ang++;
                    }

                    int negative = Random.Range(0, 2);
                    if (negative != 0)
                    {
                        ang *= -1;
                    }

                    child.Rotate(0.0f, ang, 0.0f);
                    //}
                }

                float minX, minY, minZ, maxX, maxY, maxZ;

                minX = Random.Range(-tile.minRandomDisplacement.x, tile.minRandomDisplacement.x);
                if (minX >= 0.0f)
                {
                    maxX = Random.Range(tile.minRandomDisplacement.x, tile.maxRandomDisplacement.x);
                }
                else
                {
                    maxX = Random.Range(-tile.maxRandomDisplacement.x, -tile.minRandomDisplacement.x);
                }

                minY = Random.Range(-tile.minRandomDisplacement.y, tile.minRandomDisplacement.y);
                if (minY >= 0.0f)
                {
                    maxY = Random.Range(tile.minRandomDisplacement.y, tile.maxRandomDisplacement.y);
                }
                else
                {
                    maxY = Random.Range(-tile.maxRandomDisplacement.y, -tile.minRandomDisplacement.y);
                }

                minZ = Random.Range(-tile.minRandomDisplacement.z, tile.minRandomDisplacement.z);
                if (minZ >= 0.0f)
                {
                    maxZ = Random.Range(tile.minRandomDisplacement.z, tile.maxRandomDisplacement.z);
                }
                else
                {
                    maxZ = Random.Range(-tile.maxRandomDisplacement.z, -tile.minRandomDisplacement.z);
                }

                child.Translate(
                    Random.Range(Mathf.Min(minX, maxX), Mathf.Max(minX, maxX)),
                    Random.Range(Mathf.Min(minY, maxY), Mathf.Max(minY, maxY)),
                    Random.Range(Mathf.Min(minZ, maxZ), Mathf.Max(minZ, maxZ)));
            }

            List <GameObject> toDestroy = new List <GameObject>();

            for (int i = 0; i < tile.maxRandomCopies + 1; i++)
            {
                Transform child = tile.transform.GetChild(i);
                for (int j = 0; j < tile.maxRandomCopies + 1; j++)
                {
                    Transform other = tile.transform.GetChild(j);

                    if (other != child &&
                        Vector3.Distance(other.position, child.position) < tile.minRandomDisplacement.magnitude)
                    {
                        if (!toDestroy.Contains(other.gameObject) && toDestroy.Count < tile.maxRandomCopies)
                        {
                            toDestroy.Add(other.gameObject);
                        }
                    }
                }
            }

            for (int i = 0; i < toDestroy.Count; i++)
            {
                GameObject.DestroyImmediate(toDestroy[i]);
            }
        }
    }