Inheritance: MonoBehaviour
示例#1
0
    // Use this for initialization
    void Start()
    {
        time = FindObjectOfType<GameTimeScript>();
        tile_map = FindObjectOfType<TileMapScript>();
        schedule = FindObjectOfType<ScheduleScript>();
        path_finder = gameObject.AddComponent<WorldGenerator>();

        is_moving = false;
        schedule.loadSchedule("schedule_data.bin");

        Application.runInBackground = true;
    }
示例#2
0
    void OnMouseUp()
    {
        if (newGame) {

            // clear the old save data
            if (!Directory.Exists(".\\Assets\\Resources") && File.Exists(".\\Assets\\Resources\\save_data.bin")) {
                File.Delete(".\\Assets\\Resources\\save_data.bin");
            }

            SaveDataScript.save_data = new SaveDataScript.SaveData();

            world_generator = gameObject.AddComponent<WorldGenerator>();
            schedule_generator = gameObject.AddComponent<ScheduleGenerator>();

            var map_width = 50;
            var map_height = 50;

            world_generator.generate_world("red_overworld", map_width, map_height);
            world_generator.generate_world("blue_overworld", map_width, map_height);
            world_generator.generate_world("green_overworld", map_width, map_height);
            world_generator.generate_world("purple_overworld", map_width, map_height);
            world_generator.generate_world("yellow_overworld", map_width, map_height);

            schedule_generator.generate_schedule();

            Application.LoadLevel("StartingPortalRoom");
        }
        if (loadGame) {
            var loaded = SaveDataScript.load();
            if (loaded) {
                Application.LoadLevel("StartingPortalRoom");
            }
        }
        if(addPlayer) {
            GameObject.FindGameObjectWithTag("Player").GetComponent<PauseMenuScript>().hostNetwork();
        }
        if (enterAddress) {
            Application.LoadLevel("ServerConnect");
        }
        if(connect) {
            man.networkAddress = GameObject.FindGameObjectWithTag("Text").GetComponent<Text>().text;
            Debug.Log("Adding player 2");
            Application.LoadLevel("NSceneGenTest");

        }
        if (back) {
            Destroy(GameObject.FindGameObjectWithTag("Player"));
            Application.LoadLevel("MainMenu");
        }
        if (exit) {
            Application.Quit();
        }
    }
	void Start(){
		Debug.Log ("START!");
		canvas = GameObject.Find ("MerchantCanvas").GetComponent<Canvas> () as Canvas;
		room = GameObject.Find ("RoomManager").GetComponent<RoomManager>().roomToLoad;
		textButton1 = (Text)GameObject.Find ("TextItem1").GetComponent<Text>();
		textButton2 = GameObject.Find ("TextItem2").GetComponent<Text>();
		textButton3 = GameObject.Find ("TextItem3").GetComponent<Text>();
		textButtonReload = GameObject.Find ("TextReload").GetComponent<Text>();
		playerStats = GameObject.Find ("Player").GetComponent<BasicStats>() as BasicStats;
		prefabHolder = GameObject.Find ("PrefabHolder").GetComponent<PrefabHolder> ();
		itemHolder = GameObject.Find ("ItemHolder");
		worldGenerator = GameObject.Find ("RoomManager").GetComponent<WorldGenerator> ();

		randItems = new int[3];
		if (worldGenerator.merchantItems [room.x, room.y] == null) {
			Debug.Log ("nowy klient");
			List<int> realItemPool = new List<int> ();
			realItemPool = Static.listDifference (room.itemPool, Static.itemsSpawned);
			for (int i = 0; i < randItems.GetLength(0); i++) {
				if (realItemPool.Count == 0) {
					randItems [i] = -1;
					continue;
				}
				randItems [i] = realItemPool [Static.randomIdxFromList<int> (realItemPool)];
				realItemPool.Remove (randItems [i]);
			}
			worldGenerator.merchantItems [room.x, room.y] = new List<int> ();
			for(int i = 0; i < randItems.GetLength(0); i++){
				worldGenerator.merchantItems [room.x, room.y].Add (randItems [i]);
				if(randItems[i] != -1)
					Static.itemsSpawned.Add (randItems[i]);
			}
			foreach(int x in worldGenerator.merchantItems[room.x, room.y]){
				Debug.Log ("generated:" + x);
			}
		} 
		else {
			Debug.Log("staly klient");
			for(int i = 0; i < randItems.GetLength(0); i++) {
				randItems[i] = worldGenerator.merchantItems [room.x, room.y][i];
			}
			foreach(int x in randItems){
				Debug.Log ("Contains2: " + x);
			}
		}
		//Debug.Log ("wtf button names " + randItems[0]+" "+randItems[1]+" "+randItems[2]);
		//Debug.Log (Static.items [randItems [0]].name + " " + Static.items [randItems [1]].name + " " + Static.items [randItems [2]].name);
		//Debug.Log (Static.items [randItems [0]].cost + " " + Static.items [randItems [1]].cost + " " + Static.items [randItems [2]].cost);
	}
示例#4
0
        public static GameObject CreateWorld(string name, long seed, WorldGenerator<VoxelData> worldGenerator, IMesher mesher)
        {
            GameObject ob = new GameObject("World-" + name, typeof(Terrain.World));
            ob.transform.position = Vector3.zero;
            ob.transform.rotation = Quaternion.identity;

            Terrain.World world = ob.GetComponent<Terrain.World>();
            world.Seed = seed;
            world.Mesher = mesher;
            world.WorldGenerator = worldGenerator;
            world.GenerateWorld();

            LoadedWorlds[name] = ob;
            return ob;
        }
示例#5
0
    void Start()
    {
        wg = GameObject.Find("WorldGenerator").GetComponent<WorldGenerator>();
        pi = GetComponent<PlayerInventory>();
        pd = GetComponent<PlayerData>();

        ActionCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        ActionCube.name = "ActionCube";
        ActionCube.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
        ActionCube.GetComponent<Collider>().isTrigger = true;
        ActionCube.GetComponent<Renderer>().material.color = Color.black;

        ac = ActionCube.AddComponent<ActionCube>();

        Rigidbody ac_r = ActionCube.AddComponent<Rigidbody>();
        ac_r.useGravity = false;
    }
 void Awake()
 {
     hpScript = GetComponent<HealthScript> ();
     sprite = GetComponent<SpriteRenderer> ();
     player = GameObject.FindGameObjectWithTag ("Player");
     WorldGen = GameObject.Find ("WorldGenerator").GetComponent<WorldGenerator>();
     float size = Random.Range (minSize, maxSize);
     float torque = Random.Range (minTorque, maxTorque);
     float force = Random.Range (minForce, maxForce);
     transform.Rotate(0.0f, 0.0f, Random.Range(0.0f, 360.0f));
     transform.localScale = new Vector3 (size, size, size);
     rb = GetComponent<Rigidbody2D> ();
     rb.mass = size * 2000;
     rb.AddTorque (torque, ForceMode2D.Impulse);
     rb.AddForce (transform.up * force, ForceMode2D.Impulse);
     hpScript.maxHp = Mathf.RoundToInt(30 * size);
     hpScript.hp = Mathf.RoundToInt(hpScript.maxHp - Random.Range (0, hpScript.maxHp));
 }
        public static Server create(Boolean singleplayer)
        {
            Server s = new Server();

            var map = new GameModeFortress.InfiniteMapChunked();
            map.chunksize = 32;
            var generator = new WorldGenerator();
            map.generator = generator;
            s.chunksize = 32;
            map.Reset(10000, 10000, 128);
            s.map = map;
            s.generator = generator;
            s.data = new GameDataTilesManicDigger();
            s.craftingtabletool = new CraftingTableTool() { map = map };
            s.LocalConnectionsOnly = singleplayer;

            return s;
        }
示例#8
0
    void Start()
    {
        Generator = GetComponent<WorldGenerator> ();
        Visualiser = GetComponent<WorldVisualiser>(); //Временно

        // Это всё временно, как пример. На самом деле карта должна создаваться только при начале новой игры, иначе загружаться из сохранения.
        //--
        GlobalMap = new Map (Generator.GlobalMapSize);

        Generator.CreateHeightmap (GlobalMap.MatrixHeight, Generator.LandscapeRoughness);
        Generator.CreateHeightmap (GlobalMap.MatrixForest, Generator.ForestRoughness);
        Generator.CreateRivers (GlobalMap.MatrixHeight, GlobalMap.MatrixRiver);

        CurrentMap = GlobalMap;

        //Visualiser.RenderNewMap(CurrentMap);
        Visualiser.RenderVisibleHexes(new Vector2(5,5),GameObject.FindWithTag("Player").GetComponent<PlayerData>().ViewDistance,CurrentMap);
        //--
    }
    public override void OnInspectorGUI()
    {
        WorldGenerator     generator = (WorldGenerator)target;
        SerializedProperty property;

        EditorGUILayout.LabelField("Floor");
        generator.floor = (GameObject)EditorGUILayout.ObjectField("Floor", generator.floor, typeof(GameObject), true);
        property        = serializedObject.FindProperty("floorMats");
        EditorGUILayout.PropertyField(property, new GUIContent("Floor Mats"), true);
        property = serializedObject.FindProperty("floorMatChances");
        EditorGUILayout.PropertyField(property, new GUIContent("Floor Mat Chances"), true);

        EditorGUILayout.LabelField("Walls");
        generator.wall = (GameObject)EditorGUILayout.ObjectField("Wall", generator.wall, typeof(GameObject), true);
        property       = serializedObject.FindProperty("wallMats");
        EditorGUILayout.PropertyField(property, new GUIContent("Wall Mats"), true);
        property = serializedObject.FindProperty("wallMatChances");
        EditorGUILayout.PropertyField(property, new GUIContent("Wall Mat Chances"), true);

        EditorGUILayout.LabelField("Liquid");
        generator.liquid = (GameObject)EditorGUILayout.ObjectField("Liquid", generator.liquid, typeof(GameObject), true);
        property         = serializedObject.FindProperty("liquidMats");
        EditorGUILayout.PropertyField(property, new GUIContent("Liquid Mats"), true);
        property = serializedObject.FindProperty("liquidMatChances");
        EditorGUILayout.PropertyField(property, new GUIContent("Liquid Mat Chances"), true);


        EditorGUILayout.LabelField("Rock");
        generator.rock       = (GameObject)EditorGUILayout.ObjectField("Rock", generator.rock, typeof(GameObject), true);
        generator.rockPrefab = (GameObject)EditorGUILayout.ObjectField("Rock Prefab", generator.rockPrefab, typeof(GameObject), true);
        property             = serializedObject.FindProperty("rockMats");
        EditorGUILayout.PropertyField(property, new GUIContent("Rock Mats"), true);
        property = serializedObject.FindProperty("rockMatChances");
        EditorGUILayout.PropertyField(property, new GUIContent("Rock Mat Chances"), true);
        generator.rockSpawnChance = EditorGUILayout.FloatField("Spawn Chance", generator.rockSpawnChance);

        if (GUILayout.Button("Generate Environment"))
        {
            generator.CreateEnvironmentMats();
        }
    }
示例#10
0
        protected override void LoadContent()
        {
            base.LoadContent();

            var rand = new Random();

            this.Overworld = WorldGenerator.GenerateOverworld(rand, 100, 100, rand.Next());
            this.CaveWorld = WorldGenerator.GenerateCaves(rand, 100, 100, rand.Next());

            this.Player = new Player(this.Overworld);
            this.Player.AddToInventory(new ItemStack(Item.Workbench));
            this.Player.Spawn();
            this.CurrentWorld.Entities.Add(this.Player);

            this.Camera = new Camera(this.GraphicsDevice)
            {
                Scale = 80,
                AutoScaleWithScreen = true
            };

            Font = LoadContent <SpriteFont>("Fonts/Font");
            this.UiSystem.GlobalScale         = 5;
            this.UiSystem.AutoScaleWithScreen = true;
            this.UiSystem.Style = new UntexturedStyle(this.SpriteBatch)
            {
                TextScale = 0.125F,
                Font      = new GenericSpriteFont(Font)
            };

            var hotbar = new Group(Anchor.BottomCenter, new Vector2(this.Player.Inventory.Length * 16, 16), false)
            {
                PositionOffset = new Vector2(0, 5),
                IgnoresMouse   = false
            };

            for (var i = 0; i < this.Player.Inventory.Length; i++)
            {
                hotbar.AddChild(new ItemSlot(Anchor.AutoInline, new Vector2(16), this.Player.Inventory, i));
            }
            this.UiSystem.Add("Hotbar", hotbar);
        }
示例#11
0
        public static bool Prefix(ref WorldGenerator __instance, ref List <WorldGenerator.River> __result)
        {
            UnityEngine.Random.State state = UnityEngine.Random.state;
            UnityEngine.Random.InitState(__instance.m_riverSeed);
            DateTime now = DateTime.Now;
            List <WorldGenerator.River> list  = new List <WorldGenerator.River>();
            List <UnityEngine.Vector2>  list2 = new List <UnityEngine.Vector2>(__instance.m_lakes);

            while (list2.Count > 1)
            {
                UnityEngine.Vector2 vector = list2[0];
                int num = __instance.FindRandomRiverEnd(list, __instance.m_lakes, vector, WorldGenOptions.GenOptions.usingData.riverMultipleMaxDistance, 0.4f, 128f);
                if (num == -1 && !__instance.HaveRiver(list, vector))
                {
                    num = __instance.FindRandomRiverEnd(list, __instance.m_lakes, vector, 5000f, 0.4f, 128f);
                }
                if (num != -1)
                {
                    WorldGenerator.River river = new WorldGenerator.River();
                    river.p0       = vector;
                    river.p1       = __instance.m_lakes[num];
                    river.center   = (river.p0 + river.p1) * 0.5f;
                    river.widthMax = UnityEngine.Random.Range(WorldGenOptions.GenOptions.usingData.riverWidthMaxLowerRange, WorldGenOptions.GenOptions.usingData.riverWidthMaxUpperRange);
                    river.widthMin = UnityEngine.Random.Range(WorldGenOptions.GenOptions.usingData.riverWidthMinLowerRange, river.widthMax);
                    float num2 = UnityEngine.Vector2.Distance(river.p0, river.p1);
                    river.curveWidth      = num2 / WorldGenOptions.GenOptions.usingData.riverCurveWidth;
                    river.curveWavelength = num2 / WorldGenOptions.GenOptions.usingData.riverWavelength;
                    list.Add(river);
                }
                else
                {
                    list2.RemoveAt(0);
                }
            }
            ZLog.Log("Rivers:" + list.Count);
            __instance.RenderRivers(list);
            ZLog.Log("River Calc time " + (DateTime.Now - now).TotalMilliseconds + " ms");
            UnityEngine.Random.state = state;
            __result = list;
            return(false);
        }
示例#12
0
        private void RegenerateWorld(int seed)
        {
            this._worldGen = new WorldGenerator(new Size(256, 256), seed); // 340, 340

            this._worldGen.WorldGenerationStageChanged += (text, progress) =>
            {
                this._worldGenPhase    = text;
                this._worldGenProgress = progress;
            };

            this._worldGen.WorldGenerationFinished += world =>
            {
                this.ReplaceState(new SimulationState(world));

                this._worldGen        = null;
                this._isGeneratingMap = false;

                var city     = new City("Weymouth", new Position(162, 111), 65000);
                var village1 = new Village("", new Position(160, 108), 103, city);
                var village2 = new Village("", new Position(157, 113), 46, city);
                var village3 = new Village("", new Position(158, 109), 16, city);
                city.AssociatedVillages.Add(village1);
                city.AssociatedVillages.Add(village2);
                city.AssociatedVillages.Add(village3);

                var province = new Province("", city);

                var city2 = new City("Bristol", new Position(191, 98), 150000);
                province.AssociatedCities.Add(city2);

                this._state.Provinces.Add(province);

                WorldManager.Instance.SaveWorld(this._state);
            };

            this._isGeneratingMap  = true;
            this._worldGenProgress = 0.0;
            this._worldGenPhase    = "Initializing..";

            this._worldGen.Run();
        }
    // This function is triggered when the mouse cursor is over the GameObject on which this script runs
    void OnMouseOver()
    {
        // If the left mouse button is pressed
        if (Input.GetMouseButtonDown(0))
        {
            // Display a message in the Console tab
            Debug.Log("Left click!");
            // Call method from WorldGenerator class
            WorldGenerator.CloneAndPlace(this.transform.parent.transform.position + delta, // N = C + delta
                                         this.transform.parent.gameObject);                // The parent GameObject
        }

        // If the right mouse button is pressed
        if (Input.GetMouseButtonDown(1))
        {
            // Display a message in the Console tab
            Debug.Log("Right click!");
            // Destroy the parent of the face we clicked
            Destroy(this.transform.parent.gameObject);
        }
    }
示例#14
0
        public void Init(MouseInputHandler mouseInput)
        {
            _baseScreen.RegisterEvents(mouseInput);

            GameWorld = new WorldGenerator(33, 33, 1, WorldSeed).Generate().Build();

            Hero = new Hero(Assets.GetSpecies("hero"));
            new HeroAi(Hero);

            Hero.NewActionSetEvent += _replayCaptureManager.AddReplayEvent;

            GameWorld.AddCreature(GameWorld.GetRandomEmptyPoint(0), 0, Hero);

            for (int i = 0; i < 10; i++)
            {
                Monster monster = new Monster(Assets.GetSpecies("troll"));
                new MonsterAi(monster);
                GameWorld.AddCreature(GameWorld.GetRandomEmptyPoint(0), 0, monster);
            }
            GameWorld.ComputeFov(Hero.X, Hero.Y, Hero.Depth, 12, Helpers.FovType.Shadowcast);
        }
示例#15
0
    public static WorldGenerator Create(World world, WorldMap worldMap, int pixelsPerChunk)
    {
        worldMap.sr.sortingOrder = -1;

        WorldGenerator wg = worldMap.gameObject.AddComponent <WorldGenerator>();

        int worldWidth  = world.width * pixelsPerChunk;
        int worldHeight = world.height * pixelsPerChunk;

        wg.world          = world;
        wg.pixelsPerChunk = pixelsPerChunk;
        wg.biomeLayers    = new BiomeLayer[worldWidth, worldHeight];
        wg.chunkColors    = new Color[worldWidth * worldHeight];
        wg.features       = new Feature[worldWidth, worldHeight];

        wg.texture            = new Texture2D(worldWidth, worldHeight, TextureFormat.ARGB32, false);
        wg.texture.filterMode = FilterMode.Point;
        worldMap.sr.sprite    = Sprite.Create(wg.texture, new Rect(Vector2.zero, new Vector2(worldWidth, worldHeight)), Vector2.zero);

        return(wg);
    }
示例#16
0
 protected override bool CanDoNext()
 {
     if (!base.CanDoNext())
     {
         return(false);
     }
     LongEventHandler.QueueLongEvent(() => {
         Find.GameInitData.ResetWorldRelatedMapInitData();
         Current.Game.World = WorldGenerator.GenerateWorld(this.planetCoverage, this.seedString, this.rainfall, this.temperature);
         LongEventHandler.ExecuteWhenFinished(() => {
             if (this.next != null)
             {
                 Find.WindowStack.Add(this.next);
             }
             MemoryUtility.UnloadUnusedUnityAssets();
             Find.World.renderer.RegenerateAllLayersNow();
             this.Close(true);
         });
     }, "GeneratingWorld", true, null);
     return(false);
 }
示例#17
0
    void CreatePalisade()
    {
        Vector3[] palisadePoints = VegetationGenerator.instance.GetPointsAroundCircle(transform.position, (int)buildingMaxDistanceFromOrigin / 4, buildingMaxDistanceFromOrigin + 5f);
        float     noiseAmount    = 2;

        VegetationGenerator.instance.MakeNoiseInVec3(palisadePoints, new Vector3(-noiseAmount, -noiseAmount, -noiseAmount), new Vector3(noiseAmount, noiseAmount, noiseAmount));
        palisade = new GameObject[palisadePoints.Length];
        for (int i = 0; i < palisadePoints.Length; i++)
        {
            GameObject go = Instantiate(VegetationGenerator.instance.generatedRockPrefab.gameObject);
            go.GetComponent <Rock>().generatedLeaves.GetComponent <GeneratedLeaves>().Generate();
            go.GetComponent <Rock>().generatedLeaves.GetComponent <GeneratedLeaves>().VerySlowlyConvertToFlatShading();
            go.transform.position = new Vector3(palisadePoints[i].x, transform.position.y, palisadePoints[i].z);
            VegetationGenerator.instance.PlaceObjectOnObjectUnderneath(go.transform);
            go.transform.localScale = go.transform.localScale * 2.5f * WorldGenerator.GetScaleMultiplier();
            go.AddComponent <NavMeshObstacle>().carving             = true;
            go.GetComponent <NavMeshObstacle>().carveOnlyStationary = true;
            go.GetComponent <NavMeshObstacle>().shape = NavMeshObstacleShape.Capsule;
            palisade[i] = go;
        }
    }
示例#18
0
    public void CreateGrid()
    {
        mesh         = world.GetComponent <WorldMesh>();
        generator    = world.GetComponent <WorldGenerator>();
        nodeDiameter = mesh.tileSize.x;
        nodeRadius   = nodeDiameter / 2.0f;
        gridSizeX    = generator.width;
        gridSizeY    = generator.height;
        grid         = new PathNode[gridSizeX, gridSizeY];
        Vector3 worldBottomLeft = transform.position - Vector3.right * mesh.totalSize.x / 2 - Vector3.up * mesh.totalSize.y / 2;

        for (int x = 0; x < gridSizeX; ++x)
        {
            for (int y = 0; y < gridSizeY; ++y)
            {
                Vector3           worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up * (y * nodeDiameter + nodeRadius);
                GameWorld.Terrain terrain    = world.getTerrainAtPoint(worldPoint);
                grid[x, y] = new PathNode(terrain, worldPoint, x, y);
            }
        }
    }
示例#19
0
    public Terrain getTerrainAtPoint(Vector2 position)
    {
        generator = GetComponent <WorldGenerator>();
        mesh      = GetComponent <WorldMesh>();
        Vector2 LL         = new Vector2(transform.position.x - mesh.totalSize.x / 2.0f, transform.position.y - mesh.totalSize.y / 2.0f);
        Vector2 gridSpace  = position - LL;
        Vector2 normalized = new Vector2(gridSpace.x / mesh.totalSize.x, gridSpace.y / mesh.totalSize.y);
        Vector2 tiles      = new Vector2(normalized.x * generator.width, normalized.y * generator.height);

        WorldTextureAtlas.Tiles tile = generator.tileMap[(int)tiles.x, (int)tiles.y];

        if (tile == WorldTextureAtlas.Tiles.GrassBasic)
        {
            return(Terrain.Jungle);
        }
        else if ((int)tile >= 1 && (int)tile <= 16)
        {
            return(Terrain.Water);
        }
        else if ((int)tile == 18)
        {
            return(Terrain.Forest);
        }
        else if ((int)tile == 17)
        {
            return(Terrain.Mountain);
        }
        else if ((int)tile == 19)
        {
            return(Terrain.Village);
        }
        else if ((int)tile == 20)
        {
            return(Terrain.Road);
        }
        else
        {
            return(Terrain.Jungle);
        }
    }
示例#20
0
    public override void ResolveSpriteVariant(Vector2Int p, WorldGenerator generator)
    {
        IWorldTile left       = generator.GetTileAt(new Vector2Int(p.x - 1, p.y));
        IWorldTile right      = generator.GetTileAt(new Vector2Int(p.x + 1, p.y));
        IWorldTile up         = generator.GetTileAt(new Vector2Int(p.x, p.y + 1));
        IWorldTile down       = generator.GetTileAt(new Vector2Int(p.x, p.y - 1));
        IWorldTile up_left    = generator.GetTileAt(new Vector2Int(p.x - 1, p.y + 1));
        IWorldTile up_right   = generator.GetTileAt(new Vector2Int(p.x + 1, p.y + 1));
        IWorldTile down_right = generator.GetTileAt(new Vector2Int(p.x + 1, p.y - 1));
        IWorldTile down_left  = generator.GetTileAt(new Vector2Int(p.x - 1, p.y - 1));

        SetSprite(SpriteVariant.TopLeft);

        if (!up && down)
        {
            if (!left && right)
            {
                SetSprite(SpriteVariant.TopLeft);
                return;
            }
            if (!right && left)
            {
                SetSprite(SpriteVariant.TopRight);
                return;
            }
        }
        if (up && down)
        {
            if (!left && right)
            {
                SetSprite(SpriteVariant.BottomLeft);
                return;
            }
            if (!right && left)
            {
                SetSprite(SpriteVariant.BottomRight);
                return;
            }
        }
    }
示例#21
0
    /// <summary>
    /// Initializes a new instance of the <see cref="World"/> class.
    /// </summary>
    /// <param name="width">Width in tiles.</param>
    /// <param name="height">Height in tiles.</param>
    public World(int width, int height)
    {
        // Creates an empty world.
        SetupWorld(width, height);
        int seed = UnityEngine.Random.Range(0, int.MaxValue);

        WorldGenerator.Generate(this, seed);
        Debug.ULogChannel("World", "Generated World");

        // adding air to enclosed rooms
        foreach (Room room in this.rooms)
        {
            if (room.ID > 0)
            {
                room.ChangeGas("O2", 0.2f * room.GetSize());
                room.ChangeGas("N2", 0.8f * room.GetSize());
            }
        }

        // Make one character.
        CreateCharacter(GetTileAt(Width / 2, Height / 2));
    }
    private void Awake()
    {
        visualChunks    = new List <VisualChunk>();
        visualChunkPool = new Queue <VisualChunk>();
        drawnChunks     = new Dictionary <Vector3, bool>();

        worldGenerator = GetComponent <WorldGenerator>();
        renderDistance = worldGenerator.renderDistance + 1;

        // Setup the visual chunk pool
        for (int i = 0; i < renderDistance * renderDistance * renderDistance; i++)
        {
            GameObject visualChunk = new GameObject();
            visualChunk.gameObject.name    = $"Visual Chunk {i}";
            visualChunk.transform.position = Vector3.zero;
            visualChunk.transform.parent   = transform;
            visualChunk.AddComponent <MeshFilter>();
            visualChunk.AddComponent <MeshRenderer>().material = chunkMaterial;
            visualChunk.AddComponent <MeshCollider>();
            visualChunkPool.Enqueue(visualChunk.AddComponent <VisualChunk>());
        }
    }
示例#23
0
        public WorldDataHandler GetWorldHandling()
        {
            var ret = new WorldDataHandler();

            ItemGeneratorDictionary = new ItemGeneratorDictionary();
            RegisterItemGenerators(ItemGeneratorDictionary);


            var generator = new WorldGenerator(1337, 2, Engine);
            var provider  = new SerialWorldProvider();

            if (UseFileDataStore)
            {
                var entityHandler = new EntityHandler(this, Engine, _inventoryCache);
                var chunkHandler  = new ChunkHandler(this);
                //var triggerHandler = new TriggerHandler(this);

                chunkHandler.Init();
                entityHandler.Init();

                provider.AddChunkLoader(chunkHandler);
                provider.AddEntityLoader(entityHandler);
                //provider.AddTriggerLoader(triggerHandler);

                ret.WorldSaver = new WorldSaverWrapper(entityHandler, chunkHandler, null);
                _entityHandler = entityHandler;
            }
            else
            {
                ret.WorldSaver = new WorldSaverWrapper();
            }

            provider.AddChunkLoader(generator);
            provider.AddEntityLoader(generator);
            provider.AddTriggerLoader(generator);
            ret.WorldProvider = provider;

            return(ret);
        }
示例#24
0
    public override void OnInspectorGUI()
    {
        WorldGenerator worldGen = (WorldGenerator)target;

        if (DrawDefaultInspector())
        {
            if (worldGen.AutoUpdate)
            {
                worldGen.GenerateWorld();
            }
        }

        if (GUILayout.Button("Generate"))
        {
            worldGen.GenerateWorld();
        }

        if (GUILayout.Button("Clear All Children"))
        {
            worldGen.DestroyAllChildren();
        }
    }
示例#25
0
        private void CreateBackgroundMesh(GraphicsDevice Device, BoundingBox worldBounds)
        {
            int resolution = 4;
            int width      = 256;
            int height     = 256;
            int numVerts   = (width * height) / resolution;

            BackgroundMesh = new VertexBuffer(Device, VertexPositionColor.VertexDeclaration, numVerts, BufferUsage.None);
            VertexPositionColor[] verts = new VertexPositionColor[numVerts];
            Perlin  noise     = new Perlin(MathFunctions.RandInt(0, 1000));
            Vector2 posCenter = new Vector2(width, height) * 0.5f;
            Vector3 extents   = worldBounds.Extents();
            float   scale     = 16;
            Vector3 offset    = new Vector3(extents.X, 0, extents.Z) * 0.5f * scale - new Vector3(worldBounds.Center().X, worldBounds.Min.Y, worldBounds.Center().Z);
            int     i         = 0;

            for (int x = 0; x < width; x += resolution)
            {
                for (int y = 0; y < height; y += resolution)
                {
                    float dist = MathFunctions.Clamp(
                        (new Vector2(x, y) - posCenter).Length() * 0.1f, 0, 4);

                    float landHeight = (noise.Generate(x * 0.01f, y * 0.01f)) * 8.0f * dist;
                    verts[i].Position = new Vector3(((float)x) / width * extents.X * scale,
                                                    ((int)(landHeight / 10.0f)) * 10.0f, ((float)y) / height * extents.Z * scale) - offset;
                    if (worldBounds.Contains(verts[i].Position) == ContainmentType.Contains)
                    {
                        verts[i].Position = new Vector3(verts[i].Position.X, Math.Min(verts[i].Position.Y, worldBounds.Min.Y), verts[i].Position.Z);
                    }
                    i++;
                }
            }
            BackgroundMesh.SetData(verts);
            int[] indices = WorldGenerator.SetUpTerrainIndices(width / resolution, height / resolution);
            BackgroundIndex = new IndexBuffer(Device, typeof(int), indices.Length, BufferUsage.None);
            BackgroundIndex.SetData(indices);
        }
示例#26
0
        private void GenerateNewWorld()
        {
            var g = new WorldGenerator()
                    .UsingMapGenerator(x => x
                                       .UsingDimension(2048, 2048)
                                       .UsingLandThreshold(0.3f));

            AnsiConsole.MarkupLine("[grey]Building world... standby...[/]");
            this.Game          = new Game();
            this.Game.World    = g.Next();
            this.Game.HomeCity = this.Game.World.PopulationCenters.Values.ToList().GetRandom();

            AnsiConsole.MarkupLine("[grey]Building initial character... standby...[/]");

            var names = new NameGenerator();

            var characters = new Generator <Character>()
                             .ForProperty <string>(x => x.FirstName, names)
                             .ForProperty <string>(x => x.FamilyName, names)
                             .ForEach(x =>
            {
                x.Level        = 1;
                x.Strength     = 1;
                x.Intelligence = 1;
                x.Dexterity    = 1;
                x.Resistance   = 1;
                x.Speed        = 10;
                x.Vitality     = 10;
                x.Appearance   = Chance.Roll(0.50) ? CharacterAppearance.Feminine : CharacterAppearance.Masculine;
                x.Element      = CharacterElement.Fire;
            });

            this.Game.GuildMembers.Add(characters.Next());

            AnsiConsole.MarkupLine("[grey]World generated![/]", this.Game.HomeCity.Name);

            this.GameLoop();
        }
示例#27
0
    private void Awake()
    {
        world = WorldGenerator.Instance;

        tileBlocks      = new TileBlock[world.width, world.height];
        fluidDifference = new float[world.width, world.height];

        // 블록 생성
        for (int x = 0; x < world.width; x++)
        {
            for (int y = 0; y < world.height; y++)
            {
                tileBlocks[x, y] = Instantiate(tileBlockPrefap, new Vector3(x, y, 0), Quaternion.identity, transform).GetComponent <TileBlock>();

                if (useNoise)
                {
                    float noise = CalcNoise(x, y);
                    tileBlocks[x, y].SetTileStatusByNoise(noise);
                }
                else
                {
                    tileBlocks[x, y].SetTileStatusByRandom();
                }
            }
        }

        // 인접 블록 저장
        for (int x = 0; x < world.width; x++)
        {
            for (int y = 0; y < world.height; y++)
            {
                tileBlocks[x, y].topBlock    = GetTileBlock(x, y + 1);
                tileBlocks[x, y].bottomBlock = GetTileBlock(x, y - 1);
                tileBlocks[x, y].leftBlock   = GetTileBlock(x - 1, y);
                tileBlocks[x, y].rightBlock  = GetTileBlock(x + 1, y);
            }
        }
    }
示例#28
0
    public MeshData GenerateMesh(bool createVoxels)
    {
        // so while SIZE is 16, which means theres 16 cells/blocks in grid
        // you need 17 values to be able to construct those blocks
        // (think of 17 points in a grid and the blocks are the 16 spaces in between)
        // if smoothing then need a buffer of 2 around (front and back so +4) for smoothing and normal calculation
        // (so mesh goes from 2-19 basically (0, 1, 20, 21) are not visible in final result)

#if (SMOOTH_SHADING)
        if (createVoxels)
        {
            voxels = WorldGenerator.CreateVoxels(SIZE + 5, depth, voxelSize, pos);
        }
        MeshData data = MarchingCubes.CalculateMeshData(voxels, voxelSize, 2, 2);
        data.CalculateVertexSharing();
        //Simplification simp = new Simplification(data.vertices, data.triangles);
        //data.normals = VoxelUtils.CalculateSmoothNormals(voxels, voxelSize, data.vertices);
        //data.SplitEdgesCalcSmoothness();
        data.CalculateSharedNormals();  // todo figure out why this doesnt make it smoothed...
#else
        if (createVoxels)
        {
            voxels = WorldGenerator.CreateVoxels(SIZE + 1, depth, voxelSize, worldPos);
        }

        //if (!needsMesh) {
        //    return null;
        //}

        //MeshData data = MarchingTetrahedra.CalculateMeshData(voxels, voxelSize);

        MeshData data = MarchingCubes.CalculateMeshData(voxels, voxelSize);
        data.CalculateNormals();
#endif

        //data.CalculateColorsByDepth(depth);
        return(data);
    }
示例#29
0
            private static float GetLocationModifier(Player player, float altitude)
            {
                // Forest thresholds based on logic found in MiniMap.GetMaskColor

                float forestPenalty = ForestRadiusPenalty.Value + altitude * AltitudeRadiusBonus.Value * ForestRadiusPenalty.Value;

                switch (player.GetCurrentBiome())
                {
                case Heightmap.Biome.BlackForest:
                    // Small extra penalty to account for high daylight values in black forest
                    return(-forestPenalty - 0.25f * DaylightRadiusScale.Value);

                case Heightmap.Biome.Meadows:
                    return(WorldGenerator.InForest(player.transform.position) ? -forestPenalty : 0.0f);

                case Heightmap.Biome.Plains:
                    // Small extra bonus to account for low daylight values in plains
                    return((WorldGenerator.GetForestFactor(player.transform.position) < 0.8f ? -forestPenalty : 0.0f) + 0.1f * DaylightRadiusScale.Value);

                default:
                    return(0.0f);
                }
            }
示例#30
0
    protected void MoveToBush()
    {
        float scaleMultiplier = WorldGenerator.GetScaleMultiplier();

        if (!interactionTarget)
        {
            //Debug.Log("Hello, im looking for bush");
            SetupNearestBushAsTarget();
        }
        if (!interactionTarget)
        {
            //Debug.Log("I can't find bush with food!");
            return;
        }

        float distToTarget = (transform.position - targetPos).sqrMagnitude;

        if (distToTarget <= distToCollect)
        {
            interactionTarget.GetComponent <Bush>().TakeFood(ref animalCarrying);
            interactionTarget.RemoveAnimal(this);
        }
    }
示例#31
0
    private WorldGenerator GetWorldGenerator(GameDifficultyMode difficultyMode)
    {
        WorldGenerator worldGenerator = null;

        switch (difficultyMode)
        {
        case GameDifficultyMode.Easy:
            worldGenerator = _worldGeneratorEasy;
            break;

        case GameDifficultyMode.Default:
            worldGenerator = _worldGeneratorDefault;
            break;

        case GameDifficultyMode.Hard:
            worldGenerator = _worldGeneratorHard;
            break;
        }

        Debug.Assert(worldGenerator != null, "Failed to get world generator");

        return(worldGenerator);
    }
示例#32
0
        public async Task GenerateAsync_ShowHistory()
        {
            var dice          = new LinearDice();
            var schemeService = CreateSchemeService();
            var generator     = new WorldGenerator(dice, schemeService);

            var result = await generator.GenerateGlobeAsync();

            var historyText = string.Empty;

            var iterationHistory = result.History.Items.GroupBy(x => x.Iteration).OrderBy(x => x.Key);

            foreach (var iterationHistoryGroup in iterationHistory)
            {
                historyText += $"{iterationHistoryGroup.Key} iteration" + Environment.NewLine;
                foreach (var historyItem in iterationHistoryGroup)
                {
                    historyText += historyItem.Event + Environment.NewLine;
                }
            }

            Console.WriteLine(historyText);
        }
 protected override bool CanDoNext()
 {
     if (!base.CanDoNext())
     {
         return(false);
     }
     LongEventHandler.QueueLongEvent(delegate
     {
         Find.GameInitData.ResetWorldRelatedMapInitData();
         Current.Game.World = WorldGenerator.GenerateWorld(_planetCoverage, _seedString, _rainfall, _temperature, _population, _factionCounts);
         LongEventHandler.ExecuteWhenFinished(delegate
         {
             if (next != null)
             {
                 Find.WindowStack.Add(next);
             }
             MemoryUtility.UnloadUnusedUnityAssets();
             Find.World.renderer.RegenerateAllLayersNow();
             Close();
         });
     }, "GeneratingWorld", true, null);
     return(false);
 }
示例#34
0
        public void RandomGeneration_CorrectInput_ReturnsGeneration(int rows, int columns) // method to test RandomGeneration()
        {
            // Arrange
            WorldGenerator worldGenerator = new WorldGenerator(); // create new object of worldGenerator
            WorldSize      worldSize      = new WorldSize
            {
                Rows    = rows,   // sets value for rows property in worldSize object
                Columns = columns // sets value for columns property in worldSize object
            };                    // create object of worldSize

            // Act
            WorldGenerationResult result = worldGenerator.RandomGeneration(worldSize); // execute method RandomGeneration() in worldGenerator object with worldSize parameter and save it to result

            // Assert
            var actualWorldSize           = result.Generation.WorldSize();
            var expectedLifeCells         = result.Generation.LifesCount();
            var expectedIsGenerationAlive = expectedLifeCells > 0;

            Assert.Equal(rows, actualWorldSize.Rows);
            Assert.Equal(columns, actualWorldSize.Columns);
            Assert.Equal(expectedLifeCells, result.AliveCells);
            Assert.Equal(expectedIsGenerationAlive, result.IsGenerationAlive);
        }
示例#35
0
            private static Color GetMaskColor(float wx, float wy, float height, Heightmap.Biome biome)
            {
                Color noForest = new Color(0f, 0f, 0f, 0f);
                Color forest   = new Color(1f, 0f, 0f, 0f);

                if (height < ZoneSystem.instance.m_waterLevel)
                {
                    return(noForest);
                }

                if (biome == Heightmap.Biome.Meadows)
                {
                    if (!WorldGenerator.InForest(new Vector3(wx, 0f, wy)))
                    {
                        return(noForest);
                    }

                    return(forest);
                }

                if (biome == Heightmap.Biome.Plains)
                {
                    if (WorldGenerator.GetForestFactor(new Vector3(wx, 0f, wy)) >= 0.8f)
                    {
                        return(noForest);
                    }

                    return(forest);
                }

                if (biome == Heightmap.Biome.BlackForest || biome == Heightmap.Biome.Mistlands)
                {
                    return(forest);
                }

                return(noForest);
            }
示例#36
0
    void CreateNewAnimal(AnimalSettings animalSettings)
    {
        Animal animalPrefabToSpawn = null;

        switch (animalSettings.animalType)
        {
        case AnimalSettings.AnimalType.Land:
            animalPrefabToSpawn = AnimalsManager.instance.landAnimalPrefab;
            break;

        case AnimalSettings.AnimalType.Air:
            animalPrefabToSpawn = AnimalsManager.instance.airAnimalPrefab;
            break;

        default:
            break;
        }

        GameObject   newAnimal   = Instantiate(animalPrefabToSpawn.gameObject);
        NavMeshAgent animalAgent = newAnimal.GetComponent <NavMeshAgent>();

        if (animalAgent)
        {
            animalAgent.Warp(transform.position + new Vector3(0, 1, 0));
        }
        else
        {
            newAnimal.transform.position = transform.position;
        }
        newAnimal.transform.SetParent(TerrainGenerator.instance.transform.parent);
        newAnimal.transform.localScale *= WorldGenerator.GetScaleMultiplier();
        Animal animal = newAnimal.GetComponent <Animal>();

        animal.FirstGeneration(animalSettings);
        animal.SetNest(this);
        animals.Add(animal);
    }
    /// <summary>
    /// <inheritdoc/>
    /// <para>
    /// Based on <c>HeightmapBuilder.Build</c>, but instead of calculating
    /// a full grid of 65*65 heights, only the requested position is calculated.
    /// </para>
    /// </summary>
    public float Height(Vector2i zoneLocalCoordinate)
    {
        int y = zoneLocalCoordinate.y;
        int x = zoneLocalCoordinate.x;

        Vector3 zonePos = ZonePos + new Vector3(Width * -0.5f, 0f, Width * -0.5f);

        float wy = zonePos.z + y;
        float t  = Mathf.SmoothStep(0f, 1f, y / (float)Width);

        float wx = zonePos.x + x;
        float t2 = Mathf.SmoothStep(0f, 1f, x / (float)Width);
        float value;

        WorldGenerator worldGen = WorldGenerator.instance;

        var biome = BiomeCorners[0];

        if (biome == BiomeCorners[1] &&
            biome == BiomeCorners[2] &&
            biome == BiomeCorners[3])
        {
            value = worldGen.GetBiomeHeight(biome, wx, wy);
        }
        else
        {
            float biomeHeight  = worldGen.GetBiomeHeight(biome, wx, wy);
            float biomeHeight2 = worldGen.GetBiomeHeight(BiomeCorners[1], wx, wy);
            float biomeHeight3 = worldGen.GetBiomeHeight(BiomeCorners[2], wx, wy);
            float biomeHeight4 = worldGen.GetBiomeHeight(BiomeCorners[3], wx, wy);
            float a            = Mathf.Lerp(biomeHeight, biomeHeight2, t2);
            float b            = Mathf.Lerp(biomeHeight3, biomeHeight4, t2);
            value = Mathf.Lerp(a, b, t);
        }

        return(value);
    }
示例#38
0
    private void InitializeSelectableToggle()
    {
        WorldGenerator instance      = WorldGenerator.Instance;
        int            materialCount = instance.materialPrefabs.Count;

        for (int i = 0; i < materialCount; ++i)
        {
            GameObject tmpGO = (GameObject)GameObject.Instantiate(this.exampleToogle.gameObject);
            tmpGO.SetActive(true);
            RectTransform tmpToggleTransform = tmpGO.GetComponent <RectTransform>();

            tmpToggleTransform.SetParent(this.toggleParent.transform);

            Vector2 anchoredPosition = tmpToggleTransform.anchoredPosition;
            anchoredPosition.y = this.toggleLocalInitialY + toggleLocalOffsetY * i;
            anchoredPosition.x = 0.0f;
            tmpToggleTransform.anchoredPosition = anchoredPosition;

            Text tmpToggleText = tmpGO.GetComponentInChildren <Text>();
            if (tmpToggleText != null)
            {
                tmpToggleText.text = instance.materialPrefabs[i].name;
            }

            Toggle tmpToggle = tmpGO.GetComponent <Toggle>();

            tmpToggle.isOn = instance.selectableSpawn[i];

            int index = i;
            UnityEngine.Events.UnityAction <bool> onToggle = (bool arg) =>
            {
                ToggleMaterialByIndex(index, arg);
            };

            tmpToggle.onValueChanged.AddListener(onToggle);
        }
    }
示例#39
0
    void Start()
    {
        this._lastRealTime = Time.realtimeSinceStartup;
        this._windDirectionArrowTimer = this._windDirectionArrowTimeToFadeOut;
        _windZoneObject.windMain = 0f;

        if(this._currentWorldGenerator == null)
        {
            this._currentWorldGenerator = GameObject.FindObjectOfType<WorldGenerator>();
        }

        if (this._currentWorldGenerator != null)
        {
            if (this._worldTemperatureSlider != null)
            {
                float temperatureValue = (_currentWorldGenerator.globalTemperature - WorldGenerator.globalTemperature_min) / (WorldGenerator.globalTemperature_max - WorldGenerator.globalTemperature_min);
                this._worldTemperatureSlider.value = temperatureValue;
                this._currentWorldTemperatureSliderValue = temperatureValue;

                if(this._worldTemperatureLabel != null)
                {
                    SetWorldTemperatureLabel(Mathf.Lerp(WorldGenerator.globalTemperature_min, WorldGenerator.globalTemperature_max, temperatureValue));
                }
            }
            if (this._worldWindDirectionSlider != null)
            {
                float windDirectionValue = (this._currentWorldGenerator.windDirection - WorldGenerator.windDirection_min) / (WorldGenerator.windDirection_max - WorldGenerator.windDirection_min);
                this._worldWindDirectionSlider.value = windDirectionValue;
                this._currentWindDirectionSliderValue = windDirectionValue;

                if (this._worldWindDirectionLabel != null)
                {
                    SetWindDirectionLabel(Mathf.Lerp(WorldGenerator.windDirection_min, WorldGenerator.windDirection_max, windDirectionValue));
                }
            }
            if(this._worldWindSpeedSlider != null)
            {
                float windSpeedValue = (this._currentWorldGenerator.windSpeed - WorldGenerator.windSpeed_min) / (WorldGenerator.windSpeed_max - WorldGenerator.windSpeed_min);
                this._worldWindSpeedSlider.value = windSpeedValue;
                this._currentWindSpeedSliderValue = windSpeedValue;

                if (this._worldWindSpeedLabel != null)
                {
                    SetWindSpeedLabel(Mathf.Lerp(WorldGenerator.windSpeed_min, WorldGenerator.windSpeed_max, windSpeedValue));
                }
            }

            if(this._windDirectionArrowGO != null)
            {
                Vector3 windForward = this._windDirectionArrowGO.transform.up; //arrow is rotated by 90 in pitch
                this._currentWorldGenerator.UpdateWindDirection(windForward);
            }

            if (_currentSeedLabel != null) {
                _currentSeedLabel.text = WorldGenerator.Instance.currentSeed.ToString();
            }

            if (this._worldSizeSlider != null)
            {
                int worldSizeValue = this._currentWorldGenerator.sizeX;

                this._worldSizeSlider.wholeNumbers = true;
                this._worldSizeSlider.minValue = WorldGenerator.worldSize_min;
                this._worldSizeSlider.maxValue = WorldGenerator.worldSize_max;

                this._worldSizeSlider.value = worldSizeValue;

                this._currentWorldSize = this._currentWorldGenerator.sizeX;
                this._lastWorldSize = this._currentWorldGenerator.sizeX;

                if (this._worldSizeLabel != null)
                {
                    SetWorldSizeLabel(this._currentWorldSize);
                }
            }

            if(this._seedField != null)
            {
                this._currentSeed = WorldGenerator._instance.currentSeed;
                this._seedField.text = this._currentSeed.ToString();
                this._seedField.onEndEdit.AddListener(this.OnSeedEntered);
            }
        }

        InitializeSelectableToggle();
    }
示例#40
0
    void Start()
    {
        WorldGenerator = gameObject.GetComponent<WorldGenerator> ();
        PlayerController = gameObject.GetComponent<TopDownPlayerController> ();
        Timer = gameObject.GetComponent<Timer> ();

        NextLevelMessage = Instantiate (PreFabNextLevelMessage) as GameObject;
        StartMessage = Instantiate (PreFabStartMessage) as GameObject;
        TitleMessage = Instantiate (PreFabTitleMessage) as GameObject;
        GameOverMessage = Instantiate (PreFabGameOverMessage) as GameObject;

        HideAllMessages ();
        ShowTitleText ();
    }
示例#41
0
 void Awake()
 {
     world_generator = FindObjectOfType<WorldGenerator>();
 }
示例#42
0
 public static GameObject CreateWorld(string name, WorldGenerator<VoxelData> WorldGenerator, IMesher mesher)
 {
     return CreateWorld(name, 0, WorldGenerator, mesher);
 }
    public void init(int chunkSize, int actualChunkX, int actualChunkZ, bool generateColumnsPerFrame = false)
    {
        tallestPoint = 0;
        solid = new BlockData(BlockData.BlockType.stone, new Vector3(),20);

        this.chunkSize = chunkSize;
        actualChunkCoords = new ChunkPos(actualChunkX, actualChunkZ);
        filter = gameObject.GetComponent<MeshFilter>();
        collider = gameObject.GetComponent<MeshCollider>();

        WG = GetComponentInParent<WorldGenerator>();

        bool loaded = WorldSaver.LoadChunk(this);
        if (!loaded)
        {

            Blocks = new BlockData[chunkSize, airLimit, chunkSize];

            //fill the entire array of blocks with air
            for (int x = 0; x < chunkSize; x++)
            {

                for (int y = 0; y < airLimit; y++)
                {
                    for (int z = 0; z < chunkSize; z++)
                    {
                        Blocks[x, y, z] = new BlockData(BlockData.BlockType.air, new Vector3((actualChunkX + x), y, (actualChunkZ + z)),20);
                    }
                }
            }
            CalculateChunk(actualChunkX, actualChunkZ);
        }
    }
示例#44
0
    void OnEnable()
    {
        // First thing is to se the singleton reference, many things will use this, and this object spawns pretty much everything
        instance = this;

        if(textureManager == null) {
            Debug.LogError("WorldManager Does not have a texture manager assigned! Please add one as a child and assign it to the world manager in the inspector!");
        }

        // Start by loading all data
        craftingItemState = ItemUtility.LoadCraftingItems(craftingItemFile);
        if(craftingItemState == null) {
            Debug.Log("ERROR! No crafting items found at " + craftingItemFile);
        }

        wearableItemState = ItemUtility.LoadWearableItems(wearableItemFile);
        if(wearableItemState == null) {
            Debug.Log("ERROR! No wearable items found at " + wearableItemFile);
        }

        textUtility = ProceduralTextUtility.LoadTextTypes(textSourceFile);
        if(textUtility == null) {
            Debug.Log("ERROR! No procedural text source file found at " + textSourceFile);
        }

        dieties = new Diety[NUM_DIETIES];
        for(int i = 0; i < NUM_DIETIES; i++) {
            string prefix = "";
            string title = "";
            string suffix = "";

            textUtility.GenerateCompleteName(ref prefix, ref title, ref suffix);

            Diety d = new Diety(prefix, title, suffix);
            dieties[i] = d;
        }

        // Next grabs the world generator, which should be attached to the world manager object
        worldGenerator = GetComponent<WorldGenerator>();
        if(worldGenerator == null) {
            Debug.LogWarning("WARNING! No world generator found on "+name+". No terrain will be created!");
        }

        // Grab the gramlin manager: this isnt suuuuper critical, but the game really doesnt work without it
        lootGremlinSpawnManager = GetComponent<LootGremlinSpawner>();
        if(worldGenerator == null) {
            Debug.LogWarning("WARNING! No LootGremlinSpawner found on " + name + ". No Loot gremlins will be spawned!");
        }

        uiManager = new UI_Manager();

        objectPool = new ObjectPool();

        sunLight = (Light)Instantiate(sunPrototype, new Vector3(0.0f, 0.0f, -10.0f), Quaternion.identity);
        maxSunIntensity = sunLight.intensity;

        // attempt to load game state, if it exists, otherwise create a new one
        gameState = GameStateUtility.LoadGameState(saveLocation);
        if(gameState == null) {
            gameState = new GameStateUtility();
            GameStateUtility.SaveGameState(saveLocation, gameState);
        }

        if(playerPrototype == null) {
            Debug.LogError("Player prototype is not set, cannot initialize game!");
            return;
        }
        playerStartLocation = worldGenerator.GeneratorOrigin();
        playerCharacter = (Player)Instantiate(playerPrototype, playerStartLocation, Quaternion.identity);

        // Assign the state that was loaded
        if(gameState.playerState != null) {
            playerCharacter.SetState(gameState.playerState);
        }
        else {
            Debug.Log("ERROR! Player state was not loaded / created in the game state!");
        }

        if(worldGenerator != null) {
            worldGenerator.StartGeneratingWorld(playerCharacter);
        }

        // Instaniate all of the background layers from prototypes: they are self managing
        foreach(ParallaxBackground bg in backGroundSet) {
            Instantiate(bg.gameObject);
        }

        // Fill out the ability object map with the editor assigned objects, mapped to names
        abilityObjectMap = new Dictionary<string, GameObject>();
        foreach(GameObject obj in spawnableObjects) {
            if(obj != null) {
                abilityObjectMap.Add(obj.name, obj);
            }
        }

        pawnsOnScreen = new List<Pawn>();
    }
示例#45
0
    void Start()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        col = GetComponent<MeshCollider>();
        wg = GameObject.Find("WorldGenerator").GetComponent<WorldGenerator>();

        GenerateChunk();
        BuildMesh();
        UpdateMesh();
    }
示例#46
0
    void Awake()
    {
        Instance = this;
        InitialiseTextureUpdater();

        GameObject parent = new GameObject();
        parent.name = "parent";

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                GameObject go = new GameObject();
                go.AddComponent<GridElement>();
                go.transform.position = new Vector3(x, y, 0f);
                go.AddComponent<BoxCollider2D>();
                go.transform.SetParent(parent.transform);
                //go.GetComponent<BoxCollider2D>().isTrigger = true;
                go.tag = "Node";

                GridElement gridElement = go.GetComponent<GridElement>();
                //gridElement.name = x + " - " + y;

                gridElement.m_pos = new Vector2(x, y);
                gridElement.m_node = new Node();
                gridElement.m_node.position = new Vector3(x, y, 0);
                if(x == 0 || x == mapWidth-1)
                {
                    gridElement.m_node.directions[0] = true;
                    gridElement.m_node.directions[2] = true;
                    gridElement.m_node.state = NodeState.active;
                }
                if (y == 0 || y == mapHeight-1)
                {
                    gridElement.m_node.directions[1] = true;
                    gridElement.m_node.directions[3] = true;
                    gridElement.m_node.state = NodeState.active;
                }
                if (x == 0 && y == 0)
                {
                    gridElement.m_node.directions[0] = true;
                    gridElement.m_node.directions[1] = true;
                    gridElement.m_node.directions[2] = false;
                    gridElement.m_node.directions[3] = false;
                }
                if (x == mapWidth - 1 && y == 0)
                {
                    gridElement.m_node.directions[0] = true;
                    gridElement.m_node.directions[1] = false;
                    gridElement.m_node.directions[2] = false;
                    gridElement.m_node.directions[3] = true;
                }
                if (x == 0 && y == mapHeight - 1)
                {
                    gridElement.m_node.directions[0] = false;
                    gridElement.m_node.directions[1] = true;
                    gridElement.m_node.directions[2] = true;
                    gridElement.m_node.directions[3] = false;
                }
                if (x == mapWidth - 1 && y == mapHeight - 1)
                {
                    gridElement.m_node.directions[0] = false;
                    gridElement.m_node.directions[1] = false;
                    gridElement.m_node.directions[2] = true;
                    gridElement.m_node.directions[3] = true;
                }
                grid[x, y] = gridElement;
            }
        }

        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                if (grid[x, y].m_node.state == NodeState.active)
                {
                    DrawTexture(x * 32, (mapHeight - y-1) * 32, white);
                }
                else
                {
                    DrawTexture(x * 32, (mapHeight - y-1) * 32, blank);
                }
            }

        }
    }
示例#47
0
 void Awake()
 {
     Instance = this;
 }
    private void OnWorldLoadDone(WorldGenerator.ActionType action)
    {
        playerObject = GameObject.Instantiate(playerPrefab) as GameObject;
        playerObject.SendMessage("Load",SendMessageOptions.DontRequireReceiver);
        playerObject.transform.localScale = new Vector3(0.5f,0.5f,1.0f);

        Camera.main.gameObject.AddComponent<FollowTarget>().target = playerObject;
        Camera.main.orthographicSize = 15;
    }
	void Start () {
        worldGenerator = GameObject.Find("RoomManager").GetComponent<WorldGenerator>();
	}
示例#50
0
 public void Init()
 {
     generator = new WorldGenerator ();
 }
 /// <summary>
 /// Start this instance.
 /// </summary>
 void Start()
 {
     Instance = this;
 }
示例#52
0
    void Awake()
    {
        this.sizeY = sizeX;
        SetNewWorldSize(this.sizeX, this.sizeY);

        WorldGenerator._instance = this;
        if( (this.selectableSpawn != null && this.selectableSpawn.Length != this.materialPrefabs.Count) || this.selectableSpawn == null )
        {
            int materialCount = this.materialPrefabs.Count;
            this.selectableSpawn = new bool[materialCount];
            for(int i = 0;i < materialCount;++i)
            {
                this.selectableSpawn[i] = true;
            }
        }
    }