private GameObject CreateStar(Vector2f position, float scale, ColorF color)
        {
            var star = new GameObject("Star");
            star.SetParent(this.GameObject);
            star.SetPosition2D(position);
            star.SetScale2D(scale);

            SpriteRenderer spriteRenderer = star.AddComponent<SpriteRenderer>();
            spriteRenderer.sprite = this.Sprite;
            spriteRenderer.color = color;
            spriteRenderer.sortingOrder = -10000;

            return star;
        }
 public void UpdateGraph( Font displayFont, params BarGraphElement[] graphElements ) {
     if ( Values.Length > graphElements.Length ) {
         Debug.LogWarningFormat(
             "#{0}# There are more values than there are graphElements. Not all values will be added to the graph.",
             typeof( BarGraphElement ).Name );
     }
     foreach ( RectTransform child in GraphSegments ) {
         Destroy( child.gameObject );
     }
     for ( int n = 0; n < graphElements.Length && n < Values.Length; ++n ) {
         RectTransform child =
             new GameObject( graphElements[n].name,
                             typeof( RectTransform ),
                             typeof( CanvasRenderer ),
                             typeof( Image ),
                             typeof( LayoutElement ) ).GetComponent<RectTransform>();
         if ( displayFont != null ) {
             Text textDisplay =
                 new GameObject( "TextDisplay", typeof( RectTransform ), typeof( CanvasRenderer ), typeof( Text ) )
                     .GetComponent<Text>();
             textDisplay.text = graphElements[n].Name;
             textDisplay.rectTransform.anchorMin = Vector2.zero;
             textDisplay.rectTransform.anchorMax = Vector2.one;
             textDisplay.alignment = TextAnchor.MiddleCenter;
             textDisplay.font = displayFont;
             textDisplay.resizeTextForBestFit = true;
             textDisplay.rectTransform.SetParent( child, false );
             textDisplay.rectTransform.offsetMax = Vector2.zero;
             textDisplay.rectTransform.offsetMin = Vector2.zero;
         }
         Image childImage = child.GetComponent<Image>();
         childImage.color = graphElements[n].Color;
         LayoutElement childLayout = child.GetComponent<LayoutElement>();
         childLayout.flexibleHeight = Values[n];
         child.SetParent( RectTransform, false );
     }
 }
Example #3
0
        private static ColorSlider CreateSlider(ColorValueType type)
        {
            ColorPicker picker = GetColorPicker();

            GameObject result;
            if (CreateGameObject(out result))
            {
                SetRectTransformSize(result.transform as RectTransform, 160, 20);
                result.name = "Slider_" + type.ToString();

                // Background
                CreateGradientBackground(type);

                // Handle slider area
                RectTransform handleArea = new GameObject("HandleArea").AddComponent<RectTransform>();
                handleArea.SetParent(result.transform, false);
                SetRectTransformSize(handleArea, Vector2.zero, Vector2.one, new Vector2(2.5f, 2.5f));

                // Handle
                RectTransform handleRect = new GameObject("Handle").AddComponent<RectTransform>();
                handleRect.SetParent(handleArea, false);
                handleRect.offsetMin = Vector2.zero;
                handleRect.offsetMax = Vector2.zero;
                handleRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 6f);
                Image handle = handleRect.gameObject.AddComponent<Image>();
                handle.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd");

                // Slider
                Slider slider = result.AddComponent<Slider>();
                slider.handleRect = handleRect;
                slider.targetGraphic = handle;

                // ColorSlider
                ColorSlider colorSlider = result.AddComponent<ColorSlider>();
                colorSlider.Type = type;
                colorSlider.Picker = picker;

                Selection.activeGameObject = result.gameObject;
                return colorSlider;
            }
            return null;
        }
Example #4
0
        private static void CreateCircle(ColorType anlge, ColorType distance)
        {
            ColorPicker picker = GetColorPicker();

            GameObject result;
            if (CreateGameObject(out result))
            {
                SetRectTransformSize(result.transform as RectTransform, 150, 150);
                result.name = "Circle_" + anlge + distance.ToString().Substring(distance.ToString().Length - 1);

                // Handle slider area
                RectTransform handleArea = new GameObject("HandleArea").AddComponent<RectTransform>();
                handleArea.SetParent(result.transform, false);
                SetRectTransformSize(handleArea, Vector2.zero, Vector2.one, new Vector2(6, 6));

                // Handle
                RectTransform handleRect = new GameObject("Handle").AddComponent<RectTransform>();
                handleRect.SetParent(handleArea, false);
                SetRectTransformSize(handleRect, 12, 12);
                Image handle = handleRect.gameObject.AddComponent<Image>();
                handle.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd");

                // Slider
                SliderCircle2D slider = result.AddComponent<SliderCircle2D>();
                slider.handleRect = handleRect;
                slider.targetGraphic = handle;

                // Circle
                GradientCircle circle = result.AddComponent<GradientCircle>();
                circle.ValueType1 = anlge;
                circle.ValueType2 = distance;
                circle.Picker = picker;
            }
        }
Example #5
0
        private static void CreateBox(ColorType x, ColorType y)
        {
            ColorPicker picker = GetColorPicker();

            GameObject result;
            if (CreateGameObject(out result))
            {
                SetRectTransformSize(result.transform as RectTransform, 150, 150);
                result.name = "GradientBox_" + x + y.ToString().Substring(y.ToString().Length - 1);

                // Handle slider area
                RectTransform handleArea = new GameObject("HandleArea").AddComponent<RectTransform>();
                handleArea.SetParent(result.transform, false);
                SetRectTransformSize(handleArea, Vector2.zero, Vector2.one, new Vector2(6, 6));

                // Handle
                RectTransform handleRect = new GameObject("Handle").AddComponent<RectTransform>();
                handleRect.SetParent(handleArea, false);
                SetRectTransformSize(handleRect, 12, 12);
                Image handle = handleRect.gameObject.AddComponent<Image>();
                handle.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/Knob.psd");

                // Slider
                Slider2D slider = result.AddComponent<Slider2D>();
                slider.handleRect = handleRect;
                slider.targetGraphic = handle;

                // Box
                GradientBox box = result.AddComponent<GradientBox>();
                box.ValueType1 = x;
                box.ValueType2 = y;
                box.Picker = picker;
            }
        }
Example #6
0
        private static InputField AddInput(GameObject to, float xOffset, float yOffset)
        {
            // Add image
            Image image = to.AddComponent<Image>();
            image.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/InputFieldBackground.psd");
            image.type = Image.Type.Sliced;

            InputField input = to.AddComponent<InputField>();

            // Add Text
            RectTransform textRect = new GameObject("Text").AddComponent<RectTransform>();
            textRect.SetParent(to.transform, false);
            textRect.anchorMin = new Vector2(0, 0);
            textRect.anchorMax = new Vector2(1, 1);
            textRect.offsetMin = new Vector2(xOffset, yOffset);
            textRect.offsetMax = new Vector2(-xOffset, -yOffset);
            Text text = textRect.gameObject.AddComponent<Text>();
            text.supportRichText = false;
            text.color = new Color32(50, 50, 50, 255);

            // Set image and text of inputfield
            input.targetGraphic = image;
            input.textComponent = text;

            return input;
        }
Example #7
0
        void generateMapAndPlayer(Hashtable mapInfo, PlayerSpawnDir spawnDir)
        {
            // get map information from the hash table
            string mapString = (string)mapInfo["map"];
            rows = (int)mapInfo["row"];
            columns = (int)mapInfo["column"];
            currentStageHash = (string)mapInfo["hash"];

            int HPStatus, APStatus;
            if (player != null)
            {
                HPStatus = player.m_HP;
                APStatus = player.m_AP;
            }
            else
            {
                HPStatus = (int)mapInfo["hp"];
                APStatus = (int)mapInfo["ap"];
            }

            string[] arrayMap = mapString.Split(',');

            // get item information from the hash table
            int[] itemCounts = new int[(int)(itemID.END + 1)];
            int[] itemValues = new int[(int)(itemID.END + 1)];
            for (int i = 0; i <= (int)(itemID.END); i++)
            {
                if (mapInfo.ContainsKey(i.ToString()))
                {
                    Hashtable itemTable = (Hashtable)mapInfo[i.ToString()];
                    itemCounts[i] = (int)itemTable["items"];
                    itemValues[i] = (int)itemTable["value"];
                }
                else
                {
                    itemCounts[i] = 0;
                }
            }

            // find the gates
            int northGate = -111, southGate = -111, eastGate = -111, westGate = -111;
            for (int i = 0; i < columns; i++)
            {
                if (arrayMap[i] == "N")
                {
                    northGate = i;
                    break;
                }
            }
            for (int i = 0; i < columns; i++)
            {
                if (arrayMap[columns*(rows-1) + i] == "S")
                {
                    southGate = i;
                    break;
                }
            }
            for (int i = 0; i < rows; i++)
            {
                if (arrayMap[columns - 1 + columns * (rows - 1 - i)] == "E")
                {
                    eastGate = i;
                    break;
                }
            }
            for (int i = 0; i < rows; i++)
            {
                if (arrayMap[columns * (rows - 1 - i)] == "W")
                {
                    westGate = i;
                    break;
                }
            }

            // floor generation
            for (int x = -2; x < columns + 2; x++)
            {
                for (int y = -3; y < rows + 3; y++)
                {
                    int tileIndex = 0;
                    if (x<=0 || y<=0 || x>=columns-1 || y>=rows-1)
                    {
                        tileIndex = 9;
                    }
                    else if (x == 1)
                    {
                        if (y == 1) tileIndex = 6;
                        else if (y == rows - 2) tileIndex = 0;
                        else tileIndex = 3;
                    }
                    else if (x == columns - 2)
                    {
                        if (y == 1) tileIndex = 8;
                        else if (y == rows - 2) tileIndex = 2;
                        else tileIndex = 5;
                    }
                    else
                    {
                        if (y == 1) tileIndex = 7;
                        else if (y == rows - 2) tileIndex = 1;
                        else tileIndex = 4;
                    }

                    instantiateAndAdd(floorTiles[tileIndex], x, y, holders[(int)(holderID.FLOOR)]);
                }
            }

            // cliff generation
            List<Vector3> rockTilePositions = new List<Vector3>();
            List<Vector3> rockPositions = new List<Vector3>();

            // cliff, SW side of the map
            instantiateAndAdd(cliffTiles[3], -1, -1, holders[(int)(holderID.CLIFF)]);
            for (int y = -3; y <= -2; y++)
                for (int x = -2; x <= 0; x++)
                    rockTilePositions.Add(new Vector3(x, y, 0));
            for (int y = -1; y <= 0; y++)
                rockTilePositions.Add(new Vector3(-2, y, 0));

            // cliff, SE side of the map
            instantiateAndAdd(cliffTiles[15], columns, -1, holders[(int)(holderID.CLIFF)]);
            for (int y = -3; y <= -2; y++)
                for (int x = columns-1; x<=columns+1; x++)
                    rockTilePositions.Add(new Vector3(x, y, 0));
            for (int y = -1; y <= 0; y++)
                rockTilePositions.Add(new Vector3((columns + 1), y, 0));

            // cliff, NW side of the map
            instantiateAndAdd(cliffTiles[7], -1, rows + 1, holders[(int)(holderID.CLIFF)]);
            for (int x = -2; x <= 0; x++)
                rockTilePositions.Add(new Vector3(x, rows + 2, 0));
            for (int y = rows-1; y <= rows + 1; y++)
                rockTilePositions.Add(new Vector3(-2, y, 0));

            // cliff, NE side of the map
            instantiateAndAdd(cliffTiles[11], columns, rows + 1, holders[(int)(holderID.CLIFF)]);
            for (int x = columns - 1; x <= columns + 1; x++)
                rockTilePositions.Add(new Vector3(x, rows + 2, 0));
            for (int y = rows-1; y <= rows + 1; y++)
                rockTilePositions.Add(new Vector3((columns + 1), y, 0));

            // cliff, south side
            for (int x = 1; x < columns - 1; x++)
            {
                if (x == southGate - 2)
                {
                    instantiateAndAdd(cliffTiles[2], x, -1, holders[(int)(holderID.CLIFF)]);
                    for (int y = -3; y <= -2; y++)
                        instantiateAndAdd(cliffTiles[4 + Random.Range(0, 2)], x, y, holders[(int)(holderID.CLIFF)]);
                }
                else if (x == southGate + 2)
                {
                    instantiateAndAdd(cliffTiles[14], x, -1, holders[(int)(holderID.CLIFF)]);
                    for (int y = -3; y <= -2; y++)
                        instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], x, y, holders[(int)(holderID.CLIFF)]);
                }
                else if (Mathf.Abs(x - southGate) >= 3)
                {
                    instantiateAndAdd(cliffTiles[Random.Range(0, 2)], x, -1, holders[(int)(holderID.CLIFF)]);
                    for (int y = -3; y <= -2; y++)
                        rockTilePositions.Add(new Vector3(x, y, 0));
                }
            }

            // cliff, north side
            for (int x = 1; x < columns - 1; x++)
            {
                if (x == northGate - 2)
                {
                    instantiateAndAdd(cliffTiles[6], x, rows + 1, holders[(int)(holderID.CLIFF)]);
                    instantiateAndAdd(cliffTiles[4 + Random.Range(0, 2)], x, rows + 2, holders[(int)(holderID.CLIFF)]);
                }
                else if (x == northGate + 2)
                {
                    instantiateAndAdd(cliffTiles[10], x, rows + 1, holders[(int)(holderID.CLIFF)]);
                    instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], x, rows + 2, holders[(int)(holderID.CLIFF)]);
                }
                else if (Mathf.Abs(x - northGate) >= 3)
                {
                    instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], x, rows + 1, holders[(int)(holderID.CLIFF)]);
                    rockTilePositions.Add(new Vector3(x, rows + 2, 0));
                }
            }

            // cliff, west side
            for (int y = 1; y <= rows - 1; y++)
            {
                if (y == westGate + 3)
                {
                    instantiateAndAdd(cliffTiles[6], -1, y, holders[(int)(holderID.CLIFF)]);
                    instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], -2, y, holders[(int)(holderID.CLIFF)]);
                }
                else if (y == westGate - 1)
                {
                    instantiateAndAdd(cliffTiles[2], -1, y, holders[(int)(holderID.CLIFF)]);
                    instantiateAndAdd(cliffTiles[Random.Range(0, 2)], -2, y, holders[(int)(holderID.CLIFF)]);
                }
                else if (Mathf.Abs(y - (westGate + 1)) >= 3)
                {
                    instantiateAndAdd(cliffTiles[4 + Random.Range(0, 2)], -1, y, holders[(int)(holderID.CLIFF)]);
                    rockTilePositions.Add(new Vector3(-2, y, 0));
                }
            }

            // cliff, east side
            for (int y = 1; y <= rows - 1; y++)
            {
                if (y == eastGate + 3)
                {
                    instantiateAndAdd(cliffTiles[10], columns, y, holders[(int)(holderID.CLIFF)]);
                    instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], columns + 1, y, holders[(int)(holderID.CLIFF)]);
                }
                else if (y == eastGate - 1)
                {
                    instantiateAndAdd(cliffTiles[14], columns, y, holders[(int)(holderID.CLIFF)]);
                    instantiateAndAdd(cliffTiles[Random.Range(0, 2)], columns + 1, y, holders[(int)(holderID.CLIFF)]);
                }
                else if (Mathf.Abs(y - (eastGate + 1)) >= 3)
                {
                    instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], columns, y, holders[(int)(holderID.CLIFF)]);
                    rockTilePositions.Add(new Vector3(columns + 1, y, 0));
                }
            }

            // random generation of rock tiles
            foreach (Vector3 pos in rockTilePositions)
            {
                instantiateAndAdd(
                    rockFloorTiles[Random.Range(0, rockFloorTiles.Length)],
                    Mathf.FloorToInt(pos.x),
                    Mathf.FloorToInt(pos.y),
                    holders[(int)(holderID.CLIFF)]
                );
            }

            // box colliders for the borders
            for (int x = 0; x < columns; x++)
            {
                for (int y = 0; y < rows; y++)
                {
                    if (arrayMap[x + (rows - 1 - y) * columns] == "#")
                    {
                        Transform border = new GameObject("collider").transform;
                        border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
                        border.Translate(x, y, 0);
                        border.gameObject.layer = LayerMask.NameToLayer("Object");

                        border.gameObject.AddComponent<BoxCollider2D>();
                    }
                }
            }
            if (northGate >= 1 && northGate < columns - 1)
            {
                for (int x = northGate-1; x <= northGate+1; x += 2)
                {
                    Transform border = new GameObject("collider").transform;
                    border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
                    border.Translate(x, rows + 1f, 0);
                    border.localScale += new Vector3(0, 2.0f, 0);
                    border.gameObject.layer = LayerMask.NameToLayer("Object");

                    border.gameObject.AddComponent<BoxCollider2D>();
                }
            }
            if (southGate >= 1 && southGate < columns - 1)
            {
                for (int x = southGate - 1; x <= southGate + 1; x += 2)
                {
                    Transform border = new GameObject("collider").transform;
                    border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
                    border.Translate(x, -2f, 0);
                    border.localScale += new Vector3(0, 2.0f, 0);
                    border.gameObject.layer = LayerMask.NameToLayer("Object");

                    border.gameObject.AddComponent<BoxCollider2D>();
                }
            }
            if (eastGate >= 1 && eastGate < rows - 1)
            {
                for (int y = eastGate - 1; y <= eastGate + 1; y += 2)
                {
                    Transform border = new GameObject("collider").transform;
                    border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
                    border.Translate(columns + 0.5f, y, 0);
                    border.localScale += new Vector3(1.0f, 0, 0);
                    border.gameObject.layer = LayerMask.NameToLayer("Object");

                    border.gameObject.AddComponent<BoxCollider2D>();
                }
            }
            if (westGate >= 1 && westGate < rows - 1)
            {
                for (int y = westGate - 1; y <= westGate + 1; y += 2)
                {
                    Transform border = new GameObject("collider").transform;
                    border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
                    border.Translate(-1.5f, y, 0);
                    border.localScale += new Vector3(1.0f, 0, 0);
                    border.gameObject.layer = LayerMask.NameToLayer("Object");

                    border.gameObject.AddComponent<BoxCollider2D>();
                }
            }

            // block generation
            for (int y = rows - 1; y >= 0; y--)
            {
                for (int x = 0; x < columns; x++)
                {
                    if (arrayMap[x + (rows - 1 - y) * columns] == "b")
                    {
                        instantiateAndAdd(blockTiles, x, y, 0, holders[(int)(holderID.BLOCK)]);
                    }
                }
            }

            // item generation
            for (int y = rows - 1; y >= 0; y--)
            {
                for (int x = 0; x < columns; x++)
                {
                    for (int itemIdx = (int)(itemID.START); itemIdx <= (int)(itemID.END); itemIdx++)
                    {
                        if (arrayMap[x + (rows - 1 - y) * columns] == itemIdx.ToString()
                            && itemCounts[itemIdx] > 0)
                        {
                            switch ((itemID)itemIdx)
                            {
                                case itemID.POTION1:
                                    Potion potion1 = ObjectFactory.createPotion(x, y, itemValues[itemIdx], (int)(itemID.POTION1));
                                    potion1.transform.SetParent(holders[(int)(holderID.POTION)]);
                                    break;
                                case itemID.POTION2:
                                    Potion potion2 = ObjectFactory.createPotion(x, y, itemValues[itemIdx], (int)(itemID.POTION2));
                                    potion2.transform.SetParent(holders[(int)(holderID.POTION)]);
                                    break;
                                case itemID.WEAPON:
                                    Weapon weapon = ObjectFactory.createWeapon(x, y, itemValues[itemIdx], (int)(itemID.WEAPON));
                                    weapon.transform.SetParent(holders[(int)(holderID.WEAPON)]);
                                    break;
                            }
                        }
                    }
                }
            }

            // player generation
            int playerX = 0;
            int playerY = 0;
            switch (spawnDir)
            {
                case PlayerSpawnDir.SPAWN_EAST:
                    playerX = columns - 2;
                    playerY = eastGate;
                    break;
                case PlayerSpawnDir.SPAWN_NORTH:
                    playerX = northGate;
                    playerY = rows - 2;
                    break;
                case PlayerSpawnDir.SPAWN_WEST:
                    playerX = 1;
                    playerY = westGate;
                    break;
                case PlayerSpawnDir.SPAWN_SOUTH:
                    playerX = southGate;
                    playerY = 1;
                    break;
                case PlayerSpawnDir.SPAWN_NONE:
                    bool playerPlaced = false;
                    bool hasEmptySpace = false;
                    for (int y = rows - 1; y >= 0; y--)
                    {
                        for (int x = 0; x < columns; x++)
                        {
                            if (arrayMap[x + (rows - 1 - y) * columns] == "u")
                            {
                                if (!playerPlaced)
                                {
                                    playerPlaced = true;
                                    playerX = x;
                                    playerY = y;
                                }
                            }
                            else if (arrayMap[x + (rows - 1 - y) * columns] == "f")
                            {
                                hasEmptySpace = true;
                            }
                        }
                    }
                    while (!playerPlaced && hasEmptySpace)
                    {
                        playerX = Random.Range(1, columns - 1);
                        playerY = Random.Range(1, columns - 1);
                        if (arrayMap[playerX + (rows - 1 - playerY) * columns] == "f")
                        {
                            playerPlaced = true;
                        }
                    }
                    break;
            }
            if (player == null)
            {
                player = ObjectFactory.createPlayer(playerX, playerY, HPStatus, APStatus);
                player.transform.SetParent(holders[(int)(holderID.PLAYER)]);
            }
            else
            {
                player.Initialize(playerX, playerY, HPStatus, APStatus);
            }

            // get peer's ip addresses who are in this area!
            peerIPList.Clear();
            ArrayList listIPs = (ArrayList)mapInfo["ips"];
            foreach (string ip in listIPs)
            {
                if (ip != getMyIP())
                    peerIPList.Add(ip);
            }

            // peer player initialization
            peerUDPClients.Clear();
            foreach (string ip in peerIPList)
            {
                GameObject peer = new GameObject("peer UDP client");
                UDPClient peerClient = peer.AddComponent<UDPClient>();
                peerClient.InitiateSocket(ip, 12346);
                peerUDPClients.Add(peer);

                Hashtable data = new Hashtable();
                data.Add("action", "myinfo");
                data.Add("hash", currentStageHash);
                data.Add("username", SystemInfo.deviceUniqueIdentifier);
                data.Add("ip", getMyIP());
                data.Add("xpos", playerX);
                data.Add("ypos", playerY);
                peerClient.sendJSONObject(data);
            }
        }
Example #8
0
        /// <summary>
        /// Generate Buildings on the edges of the road
        /// </summary>
        private void GenerateBuildingsOnRoad(Road road)
        {
            //create building parent if none exists
            if (_buildingParent == null)
            {
                _buildingParent = new GameObject("Buildings");
                _buildingParent.SetParent(_townParent);
            }

            var cell = road.ParentCell;
            int offset = _terrainSettings.RoadWidth;
            const float minDistance = 0.2f;

            //access building prefabs for this cell
            var prefabs = GetPrefabsForType(cell.DistrictType);

            if (prefabs == null)
            {
                return;
            }

            //Create an offset line of this road towards the inside of the cell
            var offsetLine = road.GenerateOffsetParallelTowardsPoint(offset, cell.SitePoint);

            //calculate total length of the line
            var length = offsetLine.Length();
            var traveled = minDistance * 2;

            //keep repeating until the end is reached
            while (traveled < length - (minDistance * 2))
            {
                //get point on line using normalized values [0,1]
                var pc = traveled / length;
                var pos = offsetLine.FindRandomPointOnLine(pc, pc);

                //Select a random prefab
                var prefab = prefabs.GetRandomValue();

                //Create a building site from this point
                var bs = BuildingSite.FromPoint(pos);
                bs.ParentRoad = road;

                //Spawn the building
                SpawnBuilding(pos.ToVector3(), prefab, bs);

                //travel along the line using the width of the building site
                traveled += (minDistance + bs.Width / 2);
            }
        }
        private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary<int, IDictionary<int, Sprite>> folders, ScmlObject scmlObject)
        {
            var controllerPath = string.Format ("{0}/{1}.controller", directory, entity.name);
            var animator = instance.GetComponent<Animator> (); //Fetches the prefab's Animator
            if (animator == null) animator = instance.AddComponent<Animator> (); //Or creates one if it doesn't exist
            AnimatorController controller = null;
            if (animator.runtimeAnimatorController != null) { //The controller we use is hopefully the controller attached to the animator
                controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController
                    (AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController;
            }
            if (controller == null) { //Otherwise we have to check the AssetDatabase for our controller
                controller = (AnimatorController)AssetDatabase.LoadAssetAtPath (controllerPath, typeof(AnimatorController));
                if (controller == null) {
                    controller = AnimatorController.CreateAnimatorControllerAtPath (controllerPath); //Or create a new one if it doesn't exist.
                    ProcessingInfo.NewControllers.Add (controller);
                }
                animator.runtimeAnimatorController = controller;
            }
            var transforms = new Dictionary<string, Transform> (); //All of the bones and sprites, identified by TimeLine.name, because those are truly unique
            transforms ["rootTransform"] = instance.transform; //The root GameObject needs to be part of this hierarchy as well
            var defaultBones = new Dictionary<string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation
            var defaultSprites = new Dictionary<string, SpriteInfo> (); //They are used as control values in determining whether something has changed
            var animBuilder = new AnimationBuilder (ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller);
            var firstAnim = true; //The prefab's graphic will be determined by the first frame of the first animation
            foreach (var animation in entity.animations) {
                var timeLines = new Dictionary<int, TimeLine> ();
                foreach (var timeLine in animation.timelines) //TimeLines hold all the critical data such as positioning and graphics used
                    timeLines [timeLine.id] = timeLine;
                foreach (var key in animation.mainlineKeys) {
                    var parents = new Dictionary<int, string> (); //Parents are referenced by different IDs V_V
                    parents [-1] = "rootTransform"; //This is where "-1 == no parent" comes in handy
                    var boneRefs = new Queue<Ref> (key.boneRefs ?? new Ref[0]);
                    while (boneRefs.Count > 0) {
                        var bone = boneRefs.Dequeue ();
                        var timeLine = timeLines [bone.timeline];
                        parents [bone.id] = timeLine.name;
                        if (!transforms.ContainsKey (timeLine.name)) { //We only need to go through this once, so ignore it if it's already in the dict
                            if (parents.ContainsKey (bone.parent)) { //If the parent cannot be found, it will probably be found later, so save it
                                var parentID = parents [bone.parent];
                                var parent = transforms [parentID];
                                var child = parent.Find (timeLine.name); //Try to find the child transform if it exists
                                if (child == null) { //Or create a new one
                                    child = new GameObject (timeLine.name).transform;
                                    child.SetParent (parent);
                                }
                                transforms [timeLine.name] = child;
                                var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find (timeLine.keys, x => x.id == bone.key).info;
                                if (!spatialInfo.processed) {
                                    SpatialInfo parentInfo;
                                    defaultBones.TryGetValue (parentID, out parentInfo);
                                    spatialInfo.Process (parentInfo);
                                }
                                child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f);
                                child.localRotation = spatialInfo.rotation;
                                child.localScale = new Vector3 (spatialInfo.scale_x, spatialInfo.scale_y, 1f);
                            }
                            else boneRefs.Enqueue (bone);
                        }
                    }
                    foreach (var oref in key.objectRefs) {
                        var timeLine = timeLines [oref.timeline];
                        if (!transforms.ContainsKey (timeLine.name)) { //Same as above
                            var parentID = parents [oref.parent];
                            var parent = transforms [parentID];
                            var child = parent.Find (timeLine.name);
                            if (child == null) {
                                child = new GameObject (timeLine.name).transform;
                                child.SetParent (parent);
                            }
                            transforms [timeLine.name] = child;
                            var swapper = child.GetComponent<TextureController> (); //Destroy the Sprite Swapper, we'll make a new one later
                            if (swapper != null) DestroyImmediate (swapper);
                            var renderer = child.GetComponent<SpriteRenderer> (); //Get or create a Sprite Renderer
                            if (renderer == null) renderer = child.gameObject.AddComponent<SpriteRenderer> ();
                            var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find (timeLine.keys, x => x.id == 0).info;
                            renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file];
                            if (!spriteInfo.processed) {
                                SpatialInfo parentInfo;
                                defaultBones.TryGetValue (parentID, out parentInfo);
                                spriteInfo.Process (parentInfo);
                            }
                            var spriteSize = scmlObject.GetSpriteSize(spriteInfo.folder, spriteInfo.file);

                            child.localEulerAngles = new Vector3 (0f, 0f, spriteInfo.angle);

                            child.localPosition = spriteInfo.PrefabPosition(spriteSize, spriteInfo.angle, oref.z_index); //Z-index helps determine draw order
                                            //The reason I don't use layers or layer orders is because
                            child.localScale = new Vector3 (spriteInfo.scale_x, spriteInfo.scale_y, 1f);	//There tend to be a LOT of body parts, it's better to treat
                            var color = renderer.color;												//The entity as a single sprite for layer sorting purposes.
                            color.a = spriteInfo.a;
                            renderer.color = color;
                            if (!firstAnim) child.gameObject.SetActive (false); //Disable the GameObject if this isn't the first frame of the first animation
                        }
                    }
                    if (firstAnim) firstAnim = false;
                }
                try {
                    animBuilder.Build (animation, timeLines); //Builds the currently processed AnimationClip, see AnimationBuilder for more info
                }
                catch (Exception e) {
                    Debug.LogErrorFormat ("Unable to build animation '{0}' for '{1}', reason: {2}", animation.name, entity.name, e);
                }
            }
            if (instance.GetComponent<EntityRenderer> () == null) instance.AddComponent<EntityRenderer> (); //Adds an EntityRenderer if one is not already present
            PrefabUtility.ReplacePrefab (instance, prefab, ReplacePrefabOptions.ConnectToPrefab);
            DestroyImmediate (instance); //Apply the instance's changes to the prefab, then destroy the instance.
        }
Example #10
0
        private void InitNameText()
        {
            var textTransform = _healthBar.FindChild("Name");
            if (textTransform == null)
            {
                textTransform = new GameObject("Name", typeof(Text)).transform;
                var rectTransform = textTransform.GetComponent<RectTransform>();
                rectTransform.anchorMin = new Vector2(0, 1);
                rectTransform.anchorMax = new Vector2(1, 1);
                rectTransform.sizeDelta = new Vector2(0, 16);
                rectTransform.pivot = new Vector2(.5f, 0);
                textTransform.SetParent(_healthBar, false);

                var text = textTransform.GetComponent<Text>();
                text.text = "Name";
                text.alignment = TextAnchor.MiddleCenter;
                text.gameObject.SetActive(ShowName);
                text.color = NameColor;
                text.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
                text.fontStyle = FontStyle.Bold;
                text.supportRichText = false;
                _nameText = text;
            }
            else
            {
                _nameText = textTransform.GetComponent<Text>();
            }
        }
Example #11
0
        private void InitLevelText()
        {
            var tfm = _healthBar.FindChild("Level Bg");
            if (tfm == null)
            {
                tfm = new GameObject("Level Bg", typeof (Image)).transform;
                var rectTfm = tfm.GetComponent<RectTransform>();
                rectTfm.anchorMin = new Vector2(0, .5f);
                rectTfm.anchorMax = new Vector2(0, .5f);
                rectTfm.sizeDelta = new Vector2(25, 25);
                rectTfm.pivot = new Vector2(1, .5f);
                tfm.SetParent(_healthBar, false);

                var image = tfm.GetComponent<Image>();
                image.sprite = Resources.Load<Sprite>("ENPCHealthBar-levelbg");
                image.color = Color.black;
                image.gameObject.SetActive(ShowLevel);
                _levelBg = image;
            }
            else
            {
                _levelBg = tfm.GetComponent<Image>();
            }

            tfm = _healthBar.FindChild("Level");
            if (tfm == null)
            {
                tfm = new GameObject("Level", typeof(Text)).transform;
                var rectTfm = tfm.GetComponent<RectTransform>();
                rectTfm.anchorMin = new Vector2(0, .5f);
                rectTfm.anchorMax = new Vector2(0, .5f);
                rectTfm.sizeDelta = new Vector2(25, 25);
                rectTfm.pivot = new Vector2(1, .5f);
                tfm.SetParent(_healthBar, false);

                var levelText = tfm.GetComponent<Text>();
                levelText.text = "1";
                levelText.alignment = TextAnchor.MiddleCenter;
                levelText.color = LevelColor;
                levelText.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
                levelText.fontStyle = FontStyle.Bold;
                levelText.supportRichText = false;
                levelText.gameObject.SetActive(ShowLevel);
                _levelText = levelText;
            }
            else
            {
                _levelText = tfm.GetComponent<Text>();
            }
        }
        /// <summary>
        /// Start everything up and get it configured.
        /// </summary>
        public void Start()
        {
            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                Transform textObjTransform = internalProp.FindModelTransform(transformName);
                Vector3 localScale = internalProp.transform.localScale;

                Transform offsetTransform = new GameObject().transform;
                offsetTransform.gameObject.name = "JSILabel-" + this.internalProp.propID + "-" + this.GetHashCode().ToString();
                offsetTransform.gameObject.layer = textObjTransform.gameObject.layer;
                offsetTransform.SetParent(textObjTransform, false);
                offsetTransform.Translate(transformOffset.x * localScale.x, transformOffset.y * localScale.y, 0.0f);

                textObj = offsetTransform.gameObject.AddComponent<JSITextMesh>();

                font = JUtil.LoadFont(fontName, fontQuality);

                textObj.font = font;
                //textObj.fontSize = fontQuality; // This doesn't work with Unity-embedded fonts
                textObj.fontSize = font.fontSize;

                if (!string.IsNullOrEmpty(anchor))
                {
                    if (anchor == TextAnchor.LowerCenter.ToString())
                    {
                        textObj.anchor = TextAnchor.LowerCenter;
                    }
                    else if (anchor == TextAnchor.LowerLeft.ToString())
                    {
                        textObj.anchor = TextAnchor.LowerLeft;
                    }
                    else if (anchor == TextAnchor.LowerRight.ToString())
                    {
                        textObj.anchor = TextAnchor.LowerRight;
                    }
                    else if (anchor == TextAnchor.MiddleCenter.ToString())
                    {
                        textObj.anchor = TextAnchor.MiddleCenter;
                    }
                    else if (anchor == TextAnchor.MiddleLeft.ToString())
                    {
                        textObj.anchor = TextAnchor.MiddleLeft;
                    }
                    else if (anchor == TextAnchor.MiddleRight.ToString())
                    {
                        textObj.anchor = TextAnchor.MiddleRight;
                    }
                    else if (anchor == TextAnchor.UpperCenter.ToString())
                    {
                        textObj.anchor = TextAnchor.UpperCenter;
                    }
                    else if (anchor == TextAnchor.UpperLeft.ToString())
                    {
                        textObj.anchor = TextAnchor.UpperLeft;
                    }
                    else if (anchor == TextAnchor.UpperRight.ToString())
                    {
                        textObj.anchor = TextAnchor.UpperRight;
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Unrecognized anchor '{0}' in config for {1} ({2})", anchor, internalProp.propID, internalProp.propName);
                    }
                }

                if (!string.IsNullOrEmpty(alignment))
                {
                    if (alignment == TextAlignment.Center.ToString())
                    {
                        textObj.alignment = TextAlignment.Center;
                    }
                    else if (alignment == TextAlignment.Left.ToString())
                    {
                        textObj.alignment = TextAlignment.Left;
                    }
                    else if (alignment == TextAlignment.Right.ToString())
                    {
                        textObj.alignment = TextAlignment.Right;
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Unrecognized alignment '{0}' in config for {1} ({2})", alignment, internalProp.propID, internalProp.propName);
                    }
                }

                float sizeScalar = 32.0f / (float)font.fontSize;
                textObj.characterSize = fontSize * 0.00005f * sizeScalar;
                textObj.lineSpacing = textObj.lineSpacing * lineSpacing;

                // "Normal" mode
                if (string.IsNullOrEmpty(switchTransform))
                {
                    // Force oneshot if there's no variables:
                    oneshot |= !labelText.Contains("$&$");
                    string sourceString = labelText.UnMangleConfigText();

                    if (!string.IsNullOrEmpty(sourceString) && sourceString.Length > 1)
                    {
                        // Alow a " character to escape leading whitespace
                        if (sourceString[0] == '"')
                        {
                            sourceString = sourceString.Substring(1);
                        }
                    }
                    labels.Add(new JSILabelSet(sourceString, rpmComp, oneshot));

                    if (!oneshot)
                    {
                        rpmComp.UpdateDataRefreshRate(refreshRate);
                    }
                }
                else // Switchable mode
                {
                    SmarterButton.CreateButton(internalProp, switchTransform, Click);
                    audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

                    foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                    {
                        if (node.GetValue("name") == internalProp.propName)
                        {
                            ConfigNode moduleConfig = node.GetNodes("MODULE")[moduleID];
                            ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET");

                            for (int i = 0; i < variableNodes.Length; i++)
                            {
                                try
                                {
                                    bool lOneshot = false;
                                    if (variableNodes[i].HasValue("oneshot"))
                                    {
                                        bool.TryParse(variableNodes[i].GetValue("oneshot"), out lOneshot);
                                    }
                                    if (variableNodes[i].HasValue("labelText"))
                                    {
                                        string lText = variableNodes[i].GetValue("labelText");
                                        string sourceString = lText.UnMangleConfigText();
                                        lOneshot |= !lText.Contains("$&$");
                                        labels.Add(new JSILabelSet(sourceString, rpmComp, lOneshot));
                                        if (!lOneshot)
                                        {
                                            rpmComp.UpdateDataRefreshRate(refreshRate);
                                        }
                                    }
                                }
                                catch (ArgumentException e)
                                {
                                    JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                                }
                            }
                            break;
                        }
                    }

                }

                if (!string.IsNullOrEmpty(zeroColor))
                {
                    zeroColorValue = JUtil.ParseColor32(zeroColor, part, ref rpmComp);
                    textObj.color = zeroColorValue;
                }

                bool usesMultiColor = false;
                if (!(string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(positiveColor) || string.IsNullOrEmpty(negativeColor) || string.IsNullOrEmpty(zeroColor)))
                {
                    usesMultiColor = true;
                    positiveColorValue = JUtil.ParseColor32(positiveColor, part, ref rpmComp);
                    negativeColorValue = JUtil.ParseColor32(negativeColor, part, ref rpmComp);
                    del = (Action<float>)Delegate.CreateDelegate(typeof(Action<float>), this, "OnCallback");
                    rpmComp.RegisterVariableCallback(variableName, del);
                    registeredVessel = vessel.id;

                    // Initialize the text color.  Actually, callback registration takes care of that.
                }

                if (string.IsNullOrEmpty(emissive))
                {
                    if (usesMultiColor)
                    {
                        emissiveMode = EmissiveMode.active;
                    }
                    else
                    {
                        emissiveMode = EmissiveMode.always;
                    }
                }
                else if (emissive.ToLower() == EmissiveMode.always.ToString())
                {
                    emissiveMode = EmissiveMode.always;
                }
                else if (emissive.ToLower() == EmissiveMode.never.ToString())
                {
                    emissiveMode = EmissiveMode.never;
                }
                else if (emissive.ToLower() == EmissiveMode.active.ToString())
                {
                    emissiveMode = EmissiveMode.active;
                }
                else if (emissive.ToLower() == EmissiveMode.passive.ToString())
                {
                    emissiveMode = EmissiveMode.passive;
                }
                else if (emissive.ToLower() == EmissiveMode.flash.ToString())
                {
                    if (flashRate > 0.0f)
                    {
                        emissiveMode = EmissiveMode.flash;
                        fm = JUtil.InstallFlashModule(part, flashRate);
                        if (fm != null)
                        {
                            fm.flashSubscribers += FlashToggle;
                        }
                    }
                    else
                    {
                        emissiveMode = EmissiveMode.active;
                    }
                }
                else
                {
                    JUtil.LogErrorMessage(this, "Unrecognized emissive mode '{0}' in config for {1} ({2})", emissive, internalProp.propID, internalProp.propName);
                    emissiveMode = EmissiveMode.always;
                }

                UpdateShader();
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Start failed in prop {1} ({2}) with exception {0}", e, internalProp.propID, internalProp.propName);
                labels.Add(new JSILabelSet("ERR", rpmComp, true));
            }
        }
Example #13
0
        public void ToggleShowTerrain(MapCellFlag flag, bool show)
        {
            Transform root;
            if (show)
            {
                int markIndex;
                if (!terrainRoots.TryGetValue(flag, out root))
                {
                    root = new GameObject("Terrain_" + Enum.GetName(typeof(MapCellFlag), flag)).transform;
                    root.SetParent(terrainRoot, false);
                    terrainRoots.Add(flag, root);

                    List<int> indices = terrainMaskIndices.Values.ToList();
                    for (markIndex = 0; ; ++markIndex)
                    {
                        if (indices.IndexOf(markIndex) < 0)
                            break;
                    }
                    terrainMaskIndices[flag] = markIndex;
                }
                else
                {
                    markIndex = terrainMaskIndices[flag];
                }

                root.localPosition = new Vector3(0, 0, markIndex * -0.1f);
                float scale = Mathf.Max(0.2f, 1 - markIndex * 0.2f);

                Color color = TerrainFlagInfo.GetColorByFlag(flag);
                List<MapCell> cells = GetCellsByFlag(flag);
                int cellCount = cells.Count;
                int childCount = root.childCount;
                for (int i = 0; i < cellCount; ++i)
                {
                    MapCell cell = cells[i];
                    Transform terrainMark;
                    if (i >= childCount)
                    {
                        GameObject terrainMarkObj = Loader.LoadPrefab("Map/TerrainMark").Instantiate();
                        terrainMarkObj.GetComponent<SpriteRenderer>().color = color;
                        terrainMark = terrainMarkObj.transform;
                        terrainMark.SetParent(root, false);
                    }
                    else
                    {
                        terrainMark = root.GetChild(i);
                    }
                    terrainMark.position = cell.Position;
                    terrainMark.Translate(0, 0, -terrainMark.localPosition.z);
                    terrainMark.localScale = new Vector3(scale, scale);
                }

                for (int i = cellCount; i < childCount; ++i)
                    Destroy(root.GetChild(i).gameObject);
            }
            else
            {
                if (terrainRoots.TryGetValue(flag, out root))
                {
                    Destroy(root.gameObject);
                    terrainRoots.Remove(flag);
                    terrainMaskIndices.Remove(flag);
                }
            }
        }
Example #14
0
        /// <summary>
        /// Spawn a random prop on the terrain
        /// </summary>
        private void SpawnProp(Vector3 position)
        {
            //create a parent to keep the hiearchy clean
            if (_propParent == null)
            {
                _propParent = new GameObject("Props");
                _propParent.SetParent(_townParent);
            }

            //select a random prop
            var prefab = _terrainSettings.Props.GetRandomValue();

            //Get the height of the terrain at the spawn position
            position.y = _terrain.SampleHeight(position);

            if (isOverlapping(prefab, position))
            {
                return;
            }

            //instantiate the prefab
            var prop = (GameObject)GameObject.Instantiate(prefab, position, Quaternion.identity);
            prop.SetParent(_propParent);

            //remove detail around the prop
            RemoveDetailsAroundGameObject(prop);

            //Add the prop for manual deleting
            _spawnedProps.Add(prop);
        }
Example #15
0
        internal void Init(ResourceLoader loader)
        {
            MapRoot = gameObject.transform;
            CellRoot = new GameObject("CellRoot").transform;
            CellRoot.SetParent(MapRoot, false);
            PathRoot = new GameObject("PathRoot").transform;
            PathRoot.SetParent(MapRoot, false);

            Loader = loader;
            Cells = new Dictionary<int, MapCell>();
            PathColors = new List<Color>();
            PathObjectRoots = new List<GameObject>();
            Paths = new List<MapPath>();
        }
Example #16
0
        private void InitSlider()
        {
            var sliderTransform = _healthBar.FindChild("Slider");
            if (sliderTransform == null)
            {
                sliderTransform = new GameObject("Slider", typeof(Slider)).transform;
                RectTransformFillParent(sliderTransform.GetComponent<RectTransform>());
                sliderTransform.SetParent(_healthBar, false);

                var slider = sliderTransform.GetComponent<Slider>();
                slider.interactable = false;
                slider.maxValue = MaxValue;
                slider.value = Value;
                slider.transition = Selectable.Transition.None;
                _slider = slider;
            }
            else
            {
                _slider = sliderTransform.GetComponent<Slider>();
            }

            //Background
            var fillArea = sliderTransform.FindChild("Fill Area");
            if (fillArea == null)
            {
                fillArea = new GameObject("Fill Area", typeof(RectTransform), typeof(Image)).transform;
                RectTransformFillParent(fillArea.GetComponent<RectTransform>());
                fillArea.SetParent(sliderTransform, false);

                var backImage = fillArea.GetComponent<Image>();
                backImage.sprite = Resources.Load<Sprite>("ENPCHealthBar");
                backImage.type = Image.Type.Sliced;
                backImage.color = BarBackgroundColor;
                _backImage = backImage;
            }
            else
            {
                _backImage = fillArea.GetComponent<Image>();
            }

            //Foreground
            var fill = fillArea.FindChild("Fill");
            if (fill == null)
            {
                fill = new GameObject("Fill", typeof(RectTransform), typeof(Image)).transform;
                var fillTransform = fill.GetComponent<RectTransform>();
                RectTransformFillParent(fillTransform);
                fill.SetParent(fillArea, false);

                var frontImage = fill.GetComponent<Image>();
                frontImage.sprite = _backImage.sprite;
                frontImage.type = Image.Type.Sliced;
                frontImage.color = BarColor;

                _frontImage = frontImage;
                _slider.fillRect = fillTransform;
            }
            else
            {
                _frontImage = fill.GetComponent<Image>();
            }
        }
Example #17
0
        private void InitValueText()
        {
            var valueTextTransform = _healthBar.FindChild("Value");
            if (valueTextTransform == null)
            {
                valueTextTransform = new GameObject("Value", typeof(Text)).transform;
                RectTransformFillParent(valueTextTransform.GetComponent<RectTransform>());
                valueTextTransform.GetComponent<RectTransform>().offsetMax = new Vector2(-5,0);
                valueTextTransform.SetParent(_healthBar, false);

                var valueText = valueTextTransform.GetComponent<Text>();
                valueText.text = MaxValue.ToString(CultureInfo.InvariantCulture);
                valueText.alignment = TextAnchor.MiddleRight;
                valueText.gameObject.SetActive(ShowValue);
                valueText.color = ValueColor;
                valueText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
                valueText.fontStyle = FontStyle.Bold;
                valueText.supportRichText = false;
                _valueText = valueText;
            }
            else
            {
                _valueText = valueTextTransform.GetComponent<Text>();
            }
        }
        private void Initialize(VehicleDef def, int[] colors = null)
        {
            Definition = def;

            if (colors != null && colors[0] != -1) {
                SetColors(colors);
            } else {
                var defaultClrs = CarColors.GetCarDefaults(Definition.ModelName);

                if (defaultClrs != null) {
                    SetColors(defaultClrs[UnityEngine.Random.Range(0, defaultClrs.Count)]);
                } else {
                    Debug.LogWarningFormat("No colours defined for {0}!", def.GameName);
                }
            }

            name = Definition.GameName;

            _geometryParts = Geometry.Load(Definition.ModelName,
                TextureDictionary.Load(Definition.TextureDictionaryName),
                TextureDictionary.Load("vehicle"),
                TextureDictionary.Load("misc"));

            _frames = _geometryParts.AttachFrames(transform, MaterialFlags.Vehicle);

            var wheelFrame = _frames.FirstOrDefault(x => x.Name == "wheel");

            if (wheelFrame == null) {
                Debug.LogWarningFormat("No wheels defined for {0}!", def.GameName);
                Destroy(gameObject);
                return;
            }

            foreach (var frame in _frames) {
                if (!frame.Name.StartsWith("wheel_")) continue;
                if (!frame.Name.EndsWith("_dummy")) continue;

                var childFrames = _frames.Where(x => x.ParentIndex == frame.Index);

                // disable all children of wheel dummies
                foreach (var childFrame in childFrames) {
                    childFrame.gameObject.SetActive(false);
                }

                var wheelAlignment = GetWheelAlignment(frame.Name);

                Wheel inst;

                // see if this wheel dummy has a wheel child
                var wheel = childFrames.FirstOrDefault(x => x.Name == "wheel");

                if (wheel == null) {
                    var copy = Instantiate(wheelFrame.transform);
                    copy.SetParent(frame.transform, false);

                    _wheels.Add(inst = new Wheel {
                        Alignment = wheelAlignment,
                        Parent = frame.transform,
                        Child = copy,
                    });
                } else {
                    // all children of wheel dummies get set to inactive so activate this one
                    wheel.gameObject.SetActive(true);

                    _wheels.Add(inst = new Wheel {
                        Alignment = wheelAlignment,
                        Parent = frame.transform,
                        Child = wheel.transform,
                    });
                }

                if (inst.IsLeftHand) {
                    frame.transform.Rotate(Vector3.up, 180.0f);
                }

                inst.Complement = _wheels.FirstOrDefault(x =>
                    (x.Alignment & WheelAlignment.LeftRightMask) != (inst.Alignment & WheelAlignment.LeftRightMask) &&
                    (x.Alignment & WheelAlignment.FrontMidRearMask) == (inst.Alignment & WheelAlignment.FrontMidRearMask));

                if (inst.Complement != null) {
                    inst.Complement.Complement = inst;
                }
            }

            InitializePhysics();

            foreach (var pair in _frames.Where(x => x.Name.StartsWith("door_"))) {
                var doorAlignment = GetDoorAlignment(pair.Name);

                if (doorAlignment == DoorAlignment.None) continue;

                var hinge = pair.gameObject.AddComponent<HingeJoint>();
                hinge.axis = Vector3.up;
                hinge.useLimits = true;

                var limit = 90.0f * ((doorAlignment == DoorAlignment.LeftFront || doorAlignment == DoorAlignment.LeftRear) ? 1.0f : -1.0f);
                hinge.limits = new JointLimits { min = Mathf.Min(0, limit), max = Mathf.Max(0, limit), };
                hinge.connectedBody = gameObject.GetComponent<Rigidbody>();
            }

            var frontSeat = GetPart("ped_frontseat");
            var backSeat = GetPart("ped_backseat");

            if (frontSeat != null) {
                var frontSeatMirror = new GameObject("ped_frontseat").transform;
                frontSeatMirror.SetParent(frontSeat.parent, false);
                frontSeatMirror.localPosition = Vector3.Scale(frontSeat.localPosition, new Vector3(-1f, 1f, 1f));

                if (frontSeat.localPosition.x > 0f) {
                    AttachSeat(frontSeat, SeatAlignment.FrontRight);
                    AttachSeat(frontSeatMirror, SeatAlignment.FrontLeft);
                } else {
                    AttachSeat(frontSeatMirror, SeatAlignment.FrontRight);
                    AttachSeat(frontSeat, SeatAlignment.FrontLeft);
                }

                DriverTransform = GetSeat(SeatAlignment.FrontLeft).Parent;
            }

            if (backSeat != null) {
                var backSeatMirror = new GameObject("ped_backseat").transform;
                backSeatMirror.SetParent(backSeat.parent, false);
                backSeatMirror.localPosition = Vector3.Scale(backSeat.localPosition, new Vector3(-1f, 1f, 1f));

                if (backSeat.localPosition.x > 0f) {
                    AttachSeat(backSeat, SeatAlignment.BackRight);
                    AttachSeat(backSeatMirror, SeatAlignment.BackLeft);
                } else {
                    AttachSeat(backSeatMirror, SeatAlignment.BackRight);
                    AttachSeat(backSeat, SeatAlignment.BackLeft);
                }
            }

            gameObject.SetLayerRecursive(Layer);
        }
Example #19
0
		/// <summary>
		/// Executes the baking.
		/// </summary>
		public void Bake(string trunkMeshPath, string foliageMeshPath)
		{
			//Get the root transform for the baked mesh.
			//If one tree is selected, use it.
			//Otherwise, just use the average position of all the selected trees.

			Matrix4x4 rootM;
			Vector3 avgPos = Vector3.zero;

			if (selectedBranches.Length > 1)
			{
				avgPos = selectedBranches[0].transform.position;
				for (int i = 1; i < selectedBranches.Length; ++i)
					avgPos += selectedBranches[i].transform.position;
				avgPos /= (float)selectedBranches.Length;

				rootM = Matrix4x4.TRS(-avgPos, Quaternion.identity, Vector3.one);
			}
			else
			{
				rootM = selectedBranches[0].transform.worldToLocalMatrix;
			}

			IEnumerable<TreeCurve> curves = selectedBranches.SelectMany(go => go.GetComponentsInChildren<TreeCurve>());
			

			//Create one big mesh for all the branches.
			Mesh msh = CreateMesh(curves.Select(tc => tc.GetComponent<MeshFilter>()), rootM);
			ExportOBJ(msh, trunkMeshPath, "Trunk");
			msh.Clear();

			//Create one big mesh for all the foliage.
			CurveFoliage[] cFs = curves.GetComponentsInChildren<TreeCurve, CurveFoliage>().RemoveDuplicates().ToArray();
			if (cFs.Length > 0)
			{
				if (cFs.Any(cf => cf.Mode == CurveFoliage.MeshModes.Point))
				{
					Debug.LogError("Can't currently output point foliage meshes to OBJ");
					cFs = new CurveFoliage[0];
				}
				else
				{
					msh = CreateMesh(cFs.Select(cf => cf.GetComponent<MeshFilter>()), rootM);
					ExportOBJ(msh, foliageMeshPath, "Foliage");
					msh.Clear();
				}
			}



			//Replace the current tree object with one that just has the baked assets.
			//Put the original objects inside the new one and deactivate it.

			Transform bakedObj = new GameObject("Baked Trees").transform;

			if (selectedBranches.Length > 1)
			{
				bakedObj.position = avgPos;
				bakedObj.rotation = Quaternion.identity;
				bakedObj.localScale = Vector3.one;
			}
			else
			{
				Transform oldObj = selectedBranches[0].transform;
				bakedObj.position = oldObj.position;
				bakedObj.rotation = oldObj.rotation;
				bakedObj.localScale = oldObj.localScale;
			}

			AssetDatabase.Refresh();

			Transform trunkChild = new GameObject("Trunk").transform;
			trunkChild.SetParent(bakedObj, false);
			MeshFilter mf = trunkChild.gameObject.AddComponent<MeshFilter>();
			mf.sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh>(PathUtils.GetRelativePath(trunkMeshPath,
																						  "Assets"));
			MeshRenderer mr = trunkChild.gameObject.AddComponent<MeshRenderer>();
			mr.sharedMaterial = branchMat;

			if (cFs.Length > 0)
			{
				Transform foliageChild = new GameObject("Foliage").transform;
				foliageChild.SetParent(bakedObj, false);
				mf = foliageChild.gameObject.AddComponent<MeshFilter>();
				mf.sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh>(PathUtils.GetRelativePath(foliageMeshPath,
																							  "Assets"));
				mr = foliageChild.gameObject.AddComponent<MeshRenderer>();
				mr.sharedMaterial = foliageMat;
			}
		}