public VegetationManager(Terrain terrain) { vegetationList = new List<DrawableGameComponent>(); var doc = new XmlDocument(); doc.Load(Config.VegetationConfigPath); foreach (XmlElement objectElement in doc.GetElementsByTagName("Object")) { float radius = float.Parse(objectElement.GetAttribute("boundingCylinderRadius").Replace('.',',')); float height = float.Parse(objectElement.GetAttribute("boundingCylinderHeight").Replace('.', ',')); foreach (XmlElement transformElement in objectElement.GetElementsByTagName("Transform")) { var vegetationObj = new DrawableGameComponent(radius, height); float x = float.Parse(transformElement.GetAttribute("translateX").Replace('.', ',')); float z = float.Parse(transformElement.GetAttribute("translateZ").Replace('.', ',')); float y = terrain.GetHeight(x, z); vegetationObj.Position = new Vector3(x, y, z); vegetationObj.Scale = new Vector3(float.Parse(transformElement.GetAttribute("scale").Replace('.', ','))); vegetationList.Add(vegetationObj); } } }
bool InitPathData() { GameObject terrainObj = GameObject.Find("Terrain"); terrain = terrainObj.GetComponent<Terrain>(); if (terrain == null) return false; float tWidth = terrain.terrainData.size.x; float tLength = terrain.terrainData.size.z; //----------- GameObject gridPlane = GameObject.Find ("GridPlane"); gridPlane.transform.localScale = new Vector3(tWidth*0.1f,1f,tLength*0.1f); gridPlane.transform.localPosition = new Vector3(tWidth*0.5f,0f,tLength*0.5f); //----------- Camera mainCamera = Camera.main; mainCamera.orthographicSize = Mathf.Max (tWidth*0.5f, tLength*0.5f); mainCamera.transform.position = new Vector3 (tWidth * 0.5f, 100f, tLength * 0.5f); //----------- cols = (int)(tWidth*(1f/MapVO.s_NodeSize)); rows = (int)(tLength*(1f/MapVO.s_NodeSize)); //---------- if (outFileName == "") { GameObject map = GameObject.FindWithTag ("Map"); if (map) { outFileName = map.name; loadFileName = map.name; } else { MyLogger.LogError ("Not Set Map"); return false; } } return true; }
void Start() { OriginRock = GameObject.FindWithTag ("OriginRock"); trackA = GameObject.FindWithTag ("TrackA").GetComponentsInChildren<Transform> (); trackC = GameObject.FindWithTag ("TrackC").GetComponentsInChildren<Transform> (); trackB = GameObject.FindWithTag ("TrackB").GetComponentsInChildren<Transform> (); ground = Terrain.activeTerrain; rocks = new Transform[num_rocks]; rockObjects = new GameObject[num_rocks]; for (int i = 0; i < num_rocks; i++) { int coinFlip = Random.Range (0, 3); if (coinFlip == 0){/* int objPosition = Random.Range (0, trackA.Length - 1); rocks[i] = trackA[objPosition];*/ rocks[i] = NewRock (rocks, trackA); } else if (coinFlip == 1){ /* int objPosition = Random.Range (0, trackC.Length - 1); rocks[i] = trackC[objPosition];*/ rocks[i] = NewRock(rocks, trackB); } else if (coinFlip == 2){/* int objPosition = Random.Range (0, trackB.Length - 1); rocks[i] = trackC[objPosition];*/ rocks[i] = NewRock(rocks, trackC); } rockObjects[i] = (GameObject) Instantiate(OriginRock, new Vector3 (rocks[i].position.x, rocks[i].position.y + 25f, rocks[i].position.z), Quaternion.identity); rockObjects[i].GetComponent<Renderer>().enabled = true; rockObjects[i].GetComponent<SphereCollider>().enabled = true; rockObjects[i].transform.position = new Vector3 (rocks[i].position.x, rocks[i].position.y + 25f, rocks[i].position.z); rockObjects[i].GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotation; } }
protected void apply(MapCell[,] map, List<Door> doors) { terrain = this.gameObject.GetComponent<Terrain>(); //Debug.Log ("Dimensiones del mapa de alturas:" + terrain.terrainData.heightmapWidth + "x" + terrain.terrainData.heightmapHeight); float[,] heights = terrain.terrainData.GetHeights(0, 0, terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapWidth); applyCellMap(heights, map); }
public override bool Test(Sim actor, Terrain target, bool isAutonomous, ref GreyedOutTooltipCallback greyedOutTooltipCallback) { if ((actor != null) && (actor.LotCurrent == actor.LotHome) && (Sims3.Gameplay.Queries.CountObjects<ITeleporter>(actor.LotHome) > 0x0)) { return false; } if (GoHere.Settings.mTeleportForAll) return true; if (GoHere.Settings.mVampireTeleport) { if (actor.SimDescription.IsVampire) return true; if (actor.SimDescription.IsPlayableGhost) return true; if (actor.SimDescription.IsUnicorn) return true; if (actor.SimDescription.IsGenie) return true; if (actor.SimDescription.IsFairy) return true; if (actor.SimDescription.IsWitch) return true; } return false; }
static void Main(string[] args) { Console.WriteLine("ENTER: 1 -> AutoPlayer; 2-> InteractivePlayer; 3->InteractiveWithMonters; 0->exit"); Terrain terrain = new Terrain(); IActor James; switch (Console.ReadLine()) { case "0": Environment.Exit(1); break; case "1": James = new Actor(); James.Name = "James"; terrain.ConstructAndStartGame(James, new PlayerAutoExploreStrategy(), @"ConfigurationFiles\TerrainGraph.xml"); break; case "2": James = new Player(); James.ConstuctActor(@"ConfigurationFiles\PlayerConfiguration.xml"); terrain.ConstructAndStartGame(James, new InteractiveStrategy(), @"ConfigurationFiles\InteractiveTerrainGraph.xml"); break; case "3": James = new Player(); James.ConstuctActor(@"ConfigurationFiles\PlayerConfiguration.xml"); terrain.ConstructAndStartGame(James, new MultiCreatureAndExploreStrategy(new InteractiveStrategy()), @"ConfigurationFiles\MultiCreaturesTerrain.xml"); Console.WriteLine("With Monsters"); break; default: Console.WriteLine("Not valid choise. To Start again press 1 and then enter"); if (Console.ReadLine() == "1") Main(args); break; } Console.ReadKey(); }
public GamePlay(ContentManager contentManager) { //cManager.RootDirectory = "Content"; //Console.WriteLine("Content Manager root directory: "+cManager.RootDirectory.ToString()); //paddle = cManager.Load<Texture2D>(cManager.RootDirectory+"/GameAssets/breakout_paddle"); //entityList = new List<Entities.BaseEntity>(); currentKeyboardState = Keyboard.GetState(); previousKeyboardState = currentKeyboardState; currentMouseState = Mouse.GetState(); previousMouseState = Mouse.GetState(); RoughnessPosition = new Vector2(); RoughnessPosition.X = 100; RoughnessPosition.Y = 20; WaterTexture = contentManager.Load<Texture2D>("res/art/terrain/water_block"); GrassTexture = contentManager.Load<Texture2D>("res/art/terrain/grass_block"); MountainTexture = contentManager.Load<Texture2D>("res/art/terrain/mountain_block"); kootenayFont = contentManager.Load<SpriteFont>("res/fonts/kootenay"); _terrain = new Terrain("res/art/terrain/grass_block", _boxWidth, _boxHeight, Game1._DEFAULT_SCREEN_WIDTH, Game1._DEFAULT_SCREEN_HEIGHT, GrassTexture, WaterTexture, MountainTexture); _terrain.GenerateNewMap(); _unitMap = new Unit[_terrain.ArrayWidth, _terrain.ArrayHeight]; GenerateNewUnitMap(); LoadContent(contentManager); }
public void SetTextureOnTerrain(Terrain terrain) { SplatPrototype[] va_sp = new SplatPrototype[2]; va_sp[0] = new SplatPrototype(); va_sp[0].texture = (Texture2D)Resources.Load("MyTextures/"+FirstTexture); va_sp[1] = new SplatPrototype(); va_sp[1].texture = (Texture2D)Resources.Load("MyTextures/"+SecondTexture); terrain.terrainData.splatPrototypes = va_sp; int v_td_alphaMapResolution = terrain.terrainData.alphamapResolution; float[, ,] va_alphamaps = new float[v_td_alphaMapResolution, v_td_alphaMapResolution, va_sp.Length]; va_alphamaps = terrain.terrainData.GetAlphamaps(0, 0, v_td_alphaMapResolution, v_td_alphaMapResolution); for (int ti = 0; ti < v_td_alphaMapResolution; ti++) { for (int tj = 0; tj < v_td_alphaMapResolution; tj++) { float y_01 = (float)tj/(float)terrain.terrainData.alphamapHeight; float x_01 = (float)ti/(float)terrain.terrainData.alphamapWidth; float height = terrain.terrainData.GetHeight(Mathf.RoundToInt(y_01 * terrain.terrainData.heightmapHeight),Mathf.RoundToInt(x_01 * terrain.terrainData.heightmapWidth) ); for (int v_tex = 0; v_tex < va_sp.Length; v_tex++) { if(height>HeightSeperation) va_alphamaps[ti,tj,v_tex] = Random.Range(0.0f, 1); } } } terrain.terrainData.SetAlphamaps(0, 0, va_alphamaps); }
private void getTerrain (){ if(Terrain.activeTerrain != null){ r_Terrain = Terrain.activeTerrain; r_TerrainData = r_Terrain.terrainData; r_TerrainPos = r_Terrain.transform.position; } }
public void Start() { terr = Terrain.activeTerrain; //get position on terrain Vector3 pos = GetRelativeTerrainPositionFromPos(this.transform.position, terr, terr.terrainData.heightmapWidth, terr.terrainData.heightmapHeight); //get the heights at this position float[,] heights = Terrain.activeTerrain.terrainData.GetHeights((int)pos.x - (int)(GetComponent<BoxCollider>().bounds.size.x), (int)pos.z - (int)(GetComponent<BoxCollider>().bounds.size.z), (int)GetComponent<BoxCollider>().bounds.size.x + 2, (int)GetComponent<BoxCollider>().bounds.size.z + 2); //Debug.Log ("x: " + ((int)pos.x - (int)(GetComponent<BoxCollider> ().bounds.size.x)) + " \nz:" + ((int)pos.z - (int)(GetComponent<BoxCollider> ().bounds.size.z))); //Debug.Log ("x1:" + ( (int)GetComponent<BoxCollider>().bounds.size.x + 2) + " \nz2:" + ((int)GetComponent<BoxCollider>().bounds.size.z + 2)); //Debug.Log ("heights size: " + heights.Length); //decrease the terrain height of where the object is by the height of the object // Debug.Log("Size: " + this.GetComponent<BoxCollider>().bounds.size.x); for (int x = 0; x < heights.GetLength(1); ++x) { for (int y = 0; y < heights.GetLength(0); ++y) { //Debug.Log("Pos: " + x + " " + y + "\nheight before:"+heights[x,y]); heights[x, y] -= GetComponent<BoxCollider>().bounds.size.y + 100; //Debug.Log("height after:"+heights[x,y]); } } terr.terrainData.SetHeights((int)pos.x - (int)GetComponent<BoxCollider>().bounds.size.x / 2 , (int)(pos.z) - (int)(GetComponent<BoxCollider>().bounds.size.z / 2), heights); }
TerrainInfo(Terrain terrain) { Terrain = terrain; Rectangle = new RectangleD((int)Terrain % 4 / 4.0 + 0.0002, (int)Terrain / 4 / 4.0 + 0.0002, 1 / 4.0 - 0.0004, 1 / 4.0 - 0.0004); }
///<summary> /// Initializes the pair handler. ///</summary> ///<param name="entryA">First entry in the pair.</param> ///<param name="entryB">Second entry in the pair.</param> public override void Initialize(BroadPhaseEntry entryA, BroadPhaseEntry entryB) { terrain = entryA as Terrain; convex = entryB as ConvexCollidable; if (terrain == null || convex == null) { terrain = entryB as Terrain; convex = entryA as ConvexCollidable; if (terrain == null || convex == null) throw new Exception("Inappropriate types used to initialize pair."); } //Contact normal goes from A to B. broadPhaseOverlap.entryA = convex; broadPhaseOverlap.entryB = terrain; UpdateMaterialProperties(convex.entity != null ? convex.entity.material : null, terrain.material); base.Initialize(entryA, entryB); }
// Use this for initialization void Start() { R = Instantiate(MainTerrain) as Terrain; R.transform.position = new Vector3(MainTerrain.terrainData.size.x,0,0); L = Instantiate(MainTerrain) as Terrain; L.transform.position = new Vector3(-MainTerrain.terrainData.size.x,0,0); T = Instantiate(MainTerrain) as Terrain; T.transform.position = new Vector3(0,0,MainTerrain.terrainData.size.z); B = Instantiate(MainTerrain) as Terrain; B.transform.position = new Vector3(0,0,-MainTerrain.terrainData.size.z); TR = Instantiate(MainTerrain) as Terrain; TR.transform.position = new Vector3(MainTerrain.terrainData.size.x,0,MainTerrain.terrainData.size.z); BR = Instantiate(MainTerrain) as Terrain; BR.transform.position = new Vector3(MainTerrain.terrainData.size.x,0,-MainTerrain.terrainData.size.z); TL = Instantiate(MainTerrain) as Terrain; TL.transform.position = new Vector3(-MainTerrain.terrainData.size.x,0,MainTerrain.terrainData.size.z); BL = Instantiate(MainTerrain) as Terrain; BL.transform.position = new Vector3(-MainTerrain.terrainData.size.x,0,-MainTerrain.terrainData.size.z); TL.SetNeighbors(null,null,T,L); T.SetNeighbors(TL,null,TR,MainTerrain); TR.SetNeighbors(T,null,null,R); L.SetNeighbors(null,TL,MainTerrain,BL); MainTerrain.SetNeighbors(L,T,R,B); R.SetNeighbors(MainTerrain,TR,null,BR); BL.SetNeighbors(null,L,B,null); B.SetNeighbors(BL,MainTerrain,BR,null); BR.SetNeighbors(B,R,null,null); }
static void Main(string[] args) { /* Player Auto explor string str = "satish"; Convert.ToInt32(str[1]); Terrain terrain = new Terrain(); terrain.PrepareTerrainFromXml(@"ConfigurationFiles\TerrainGraph.xml"); var player = new Player() { Name = "Akrem" }; terrain.Subscribe(TripRecorder.Instance); var terrainExplore = new TerrainAutoExploration(player, terrain); //Call the automated Exploration method terrainExplore.Explore(); */ // this is a test Terrain terrain = new Terrain(); terrain.PrepareInteractiveTerrainFromXml(@"ConfigurationFiles\InteractiveTerrainGraph.xml"); Player player = new Player(); player.PreparePlayerFromXml(@"ConfigurationFiles\PlayerConfiguration.xml"); terrain.InteractiveExplore(player); }
void Start() { terr = (Terrain) GetComponent(typeof(Terrain)); terr.name = "Terrain"; Tw = terr.terrainData.heightmapWidth; Th = terr.terrainData.heightmapHeight; heightMapBackup = terr.terrainData.GetHeights(0, 0, Tw, Th); initHeightMap = terr.terrainData.GetHeights(0, 0, Tw, Th); for (int i=0; i<Tw; i++) { for (int j=0; j<Th; j++) { initHeightMap[i,j] = 0;//desiredHeight;//desiredHeight; } } Debug.Log("START TERRAIN"); terr.terrainData.SetHeights(0,0,initHeightMap); Debug.Log(terr.detailObjectDistance.ToString()); Terrain.activeTerrain.detailObjectDistance = 10000; Terrain.activeTerrain.basemapDistance = 1000; //terr.detailObjectDistance = 1000; instance = this; //generateTerrain.instance.UpdateTerrainHeight(0, 0, 8.0f); //generateTerrain.instance.UpdateTerrainHeight(128, 128, 8.0f); }
public LevelGrid(Terrain ter) : this(ter.transform.position.x, ter.transform.position.y, ter.terrainData.size.x , ter.terrainData.size.z) { }
protected void paintTerrain(MapCell[,] map, Door d) { terrain = this.gameObject.GetComponent<Terrain>(); float[,,] splatmapData = new float[terrain.terrainData.alphamapWidth, terrain.terrainData.alphamapHeight, terrain.terrainData.alphamapLayers]; float[] splatWallWeights = new float[terrain.terrainData.alphamapLayers]; splatWallWeights[0] = 0f; splatWallWeights[1] = 1f; float[] splatFloorWeights = new float[terrain.terrainData.alphamapLayers]; splatFloorWeights[0] = 1f; splatFloorWeights[1] = 0f; int indexXmap, indexYmap; for (int i = 0; i < splatmapData.GetLength(0); i++) { for (int j = 0; j < splatmapData.GetLength(1); j++) { indexXmap = Mathf.Clamp(i/factor, 0, map.GetLength(0) - 1); indexYmap = Mathf.Clamp(j/factor, 0, map.GetLength(0) - 1); if (map[indexXmap, indexYmap].cellKind == MapCell.CellKind.WALL || map[indexXmap, indexYmap].cellKind == MapCell.CellKind.UNUSED) { splatmapData = setSplatWeights(i, j, splatWallWeights, splatmapData); } else { splatmapData = setSplatWeights(i, j, splatFloorWeights, splatmapData); } } } terrain.terrainData.SetAlphamaps(0, 0, splatmapData); terrain.Flush(); }
private void CreateComponents() { if (!this.assignedTerrain) { this.assignedTerrain = Terrain.activeTerrain; } this.TerrainSizeX = this.assignedTerrain.terrainData.size.x; this.TerrainSizeZ = this.assignedTerrain.terrainData.size.z; this.terrainSizeOverTexturesize = new Vector2(this.TerrainSizeX / this.DisplacementTexCoverage, this.TerrainSizeZ / this.DisplacementTexCoverage); Shader.SetGlobalVector("_AfsGrassTerrainDisplacementTexCoverage", new Vector4(this.TerrainSizeX, this.TerrainSizeZ, this.terrainSizeOverTexturesize.x, this.terrainSizeOverTexturesize.y)); float x = this.assignedTerrain.transform.position.x / this.TerrainSizeX; float y = this.assignedTerrain.transform.position.z / this.TerrainSizeZ; Shader.SetGlobalVector("_AfsGrassTerrainNormalizedPos", new Vector2(x, y)); GameObject exists = GameObject.Find("AFSGrassDisplacementCameraTest"); if (!exists) { this.DisplacementCameraGO = new GameObject("AFSGrassDisplacementCameraTest"); this.DisplacementCameraGO.transform.rotation = Quaternion.LookRotation(Vector3.down, Vector3.forward); this.createDisplacementTexture(); this.DisplacementCamera = this.DisplacementCameraGO.AddComponent<Camera>(); this.DisplacementCamera.orthographic = true; this.DisplacementCamera.orthographicSize = this.DisplacementTexCoverage * 0.5f; this.DisplacementCamera.renderingPath = RenderingPath.Forward; this.DisplacementCamera.nearClipPlane = 1f; this.DisplacementCamera.farClipPlane = 100f; this.DisplacementCamera.cullingMask = this.DisplacementLayer; this.DisplacementCamera.useOcclusionCulling = false; this.DisplacementCamera.backgroundColor = Color.black; this.DisplacementCamera.clearFlags = CameraClearFlags.Color; this.DisplacementCamera.targetTexture = this.DisplacementTexture; this.DisplacementCamera.depth = Camera.main.depth - 1f; } }
public TerrainData(Terrain topLeft, Terrain topRight, Terrain bottomLeft, Terrain bottomRight) { TopLeft = topLeft; TopRight = topRight; BottomLeft = bottomLeft; BottomRight = bottomRight; }
public TerrainInfo(int globX, int globZ, Terrain ter, Vector3 newPos) { newPosition = newPos; globalX = globX; globalZ = globZ; terrain = ter; }
// Use this for initialization void Start() { var terrainObject = Resources.Load<GameObject>("Prefabs/ClashOfSpecies/Terrains/" + manager.pendingDefenseConfig.terrain); terrain = (Instantiate(terrainObject, Vector3.zero, Quaternion.identity) as GameObject).GetComponent<Terrain>(); terrain.transform.position = Vector3.zero; terrain.transform.localScale = Vector3.one; Camera.main.GetComponent<ClashBattleCamera>().target = terrain; foreach (var species in manager.pendingDefenseConfig.layout.Keys) { var currentSpecies = species; var item = Instantiate(defenseItemPrefab) as GameObject; remaining.Add(currentSpecies.id, 5); var itemReference = item.GetComponent<ClashUnitListItem>(); var texture = Resources.Load<Texture2D>("Images/" + currentSpecies.name); itemReference.toggle.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); itemReference.toggle.onValueChanged.AddListener((val) => { if (val) { selected = currentSpecies; itemReference.toggle.GetComponent<Image>().color = new Color(1.0f, 1.0f, 1.0f, 0.5f); } else { selected = null; itemReference.toggle.GetComponent<Image>().color = new Color(1.0f, 1.0f, 1.0f, 1.0f); } }); itemReference.toggle.group = toggleGroup; item.transform.SetParent(unitList.transform); item.transform.position = new Vector3(item.transform.position.x, item.transform.position.y, 0.0f); item.transform.localScale = Vector3.one; itemReference.amountLabel.text = remaining[currentSpecies.id].ToString(); } }
public Tile(Terrain t) { Terrain = t; ReBuild = true; creatures = new HashSet<Creature>(); items = new HashSet<Item>(); }
public static void RefreshTreeTextures(Terrain terrain) { if (!terrain) { throw new NullReferenceException(); } if (!TerrainHack.RanOnce) { TerrainHack.RanOnce = true; if (TerrainHack.AbleToLocateOnTerrainChanged) { try { TerrainHack.OnTerrainChanged.Invoke(terrain, TerrainHack.TriggerTreeChangeValues); TerrainHack.Working = true; return; } catch (Exception exception) { Debug.LogException(exception); TerrainHack.Working = false; } } } if (!TerrainHack.Working) { terrain.Flush(); } else { TerrainHack.OnTerrainChanged.Invoke(terrain, TerrainHack.TriggerTreeChangeValues); } }
/// <summary> /// explores the terrain /// </summary> public void Explore(Terrain terrain, IActor actor) { this.terrain = terrain; //the Explore starts from the start location in the terrain Explore(terrain.StartLocation, actor); Console.WriteLine("**** There are no more Exits ************"); }
/// <summary> /// Generate a chunk and return it. The terrain object remains unmodified. /// </summary> /// <param name="terrain">The terrain.</param> /// <param name="chunkIndex">The chunk index.</param> /// <returns>The chunk.</returns> public Chunk GenerateChunk(Terrain terrain, Vector2I chunkIndex) { Chunk chunk = new Chunk(); // Calculate the position of the chunk in world coordinates var chunkPos = new Vector2I(chunkIndex.X * Chunk.SizeX, chunkIndex.Y * Chunk.SizeY); // Get the surface heights for this chunk int[] surfaceHeights = this.GenerateSurfaceHeights(chunkPos); // For now, fill the terrain with mud under the surface for (int x = 0; x < Chunk.SizeX; x++) { int surfaceHeight = surfaceHeights[x]; if (surfaceHeight > 0) { for (int y = 0; y < surfaceHeight; y++) { chunk[x, y] = new Block(BlockType.Dirt); } } } return chunk; }
public void GenerateHeights(Terrain terrain, float tileSize) { float[,] heightsA = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight]; float[,] heightsB = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight]; float[,] heightsC = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight]; float[,] heightsFinal = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight]; for (int i = 0; i < terrain.terrainData.heightmapWidth; i++) { for (int k = 0; k < terrain.terrainData.heightmapHeight; k++) { heightsA[i, k] = Mathf.PerlinNoise(((float)i / (float)terrain.terrainData.heightmapWidth) * (tileSize / 10), ((float)k / (float)terrain.terrainData.heightmapHeight) * (tileSize / 10)); if (heightsA[i, k] > 0.5f) heightsA[i, k] = 1.0f; else heightsA[i, k] = 0.0f; heightsA[i, k] = heightsA[i, k]; heightsB[i, k] = Mathf.PerlinNoise(((float)i / (float)terrain.terrainData.heightmapWidth) * (tileSize / 1), ((float)k / (float)terrain.terrainData.heightmapHeight) * (tileSize / 1)); heightsB[i, k] = heightsB[i, k] / 15.0f; heightsC[i, k] = Mathf.PerlinNoise(((float)i / (float)terrain.terrainData.heightmapWidth) * (tileSize / 5), ((float)k / (float)terrain.terrainData.heightmapHeight) * (tileSize / 5)); heightsC[i, k] = heightsC[i, k] / 3.0f; heightsFinal[i, k] = heightsA[i, k] + heightsB[i, k] + heightsC[i, k]; } } terrain.terrainData.SetHeights(0, 0, heightsFinal); }
/// <summary> /// Returns the zero-based index of the most dominant texture /// on the main terrain at this world position. /// </summary> public static int GetMainTerrainTexture(Vector3 worldPos, Terrain terrain) { TerrainData terrainData = terrain.terrainData; Vector3 terrainPos = terrain.transform.position; // calculate which splat map cell the worldPos falls within (ignoring y) int mapX = (int)(((worldPos.x - terrainPos.x) / terrainData.size.x) * terrainData.alphamapWidth); int mapZ = (int)(((worldPos.z - terrainPos.z) / terrainData.size.z) * terrainData.alphamapHeight); // get the splat data for this cell as a 1x1xN 3d array (where N = number of textures) float[,,] splatmapData = terrainData.GetAlphamaps(mapX,mapZ,1,1); // extract the 3D array data to a 1D array: float[] mix = new float[splatmapData.GetUpperBound(2)+1]; for (int n=0; n<mix.Length; ++n) { mix[n] = splatmapData[0,0,n]; } float maxMix = 0; int maxIndex = 0; // loop through each mix value and find the maximum for (int n=0; n<mix.Length; ++n) { if (mix[n] > maxMix) { maxIndex = n; maxMix = mix[n]; } } return maxIndex; }
void Update() { terrain = GetComponent<Terrain>(); tData = terrain ? terrain.terrainData : null; tMaterial = terrain ? terrain.materialTemplate : null; if (!terrain || !tData || !tMaterial) return; if(disableBasemap && !Application.isPlaying && GetComponent<Terrain>().basemapDistance != 1000000) // only reset on update in edit mode GetComponent<Terrain>().basemapDistance = 1000000; if (cutoutMode) { if (tMaterial.HasProperty("_CutoutModeHideAlpha") && tMaterial.GetFloat("_CutoutModeHideAlpha") != cutoutModeHideAlpha) tMaterial.SetFloat("_CutoutModeHideAlpha", cutoutModeHideAlpha); } else if (tMaterial.HasProperty("_CutoutModeHideAlpha") && tMaterial.GetFloat("_CutoutModeHideAlpha") != -1) tMaterial.SetFloat("_CutoutModeHideAlpha", -1); if (!Application.isPlaying) ApplyTransparencyMap(); else if (!transparencyMap && autoUpdateTransparencyMap) { UpdateTransparencyMap(); ApplyTransparencyMap(); } else ApplyTransparencyMap(); }
// Use this for initialization void Start() { // get terrain and size of terrain terrain = (Terrain)gameObject.GetComponent ("Terrain"); //Vector3 tSize = terrain.terrainData.size; //Debug.Log (tSize); // set perlin noise origin coordinates float xOrg = Random.Range (0, .1f); float yOrg = Random.Range (0, .1f); // get heightmap float[,] heightmap = new float[terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapHeight]; // fill array with perlin noise values for(int i=0;i<heightmap.GetLength(0);i++){ for(int j=0;j<heightmap.GetLength(1);j++){ float xCoord = xOrg + (float)i / ((float)heightmap.GetLength(0)/5); float yCoord = yOrg + (float)j / ((float)heightmap.GetLength(1)/5); heightmap[i,j] = Mathf.PerlinNoise(xCoord, yCoord); } } // reattatch array to terrain terrain.terrainData.SetHeights(0,0,heightmap); }
public void AsATerrainIShouldReceiveTheUpperBoundaryValuesAtInitialization() { var terrain = new Terrain(new Coordinate("5 5")); Assert.AreEqual(5, terrain.UpperBoundary.X); Assert.AreEqual(5, terrain.UpperBoundary.Y); }
void RayPlace(Ray ray) { IndexPosition lastCIndex = IndexPosition.Zero, lastBIndex = new IndexPosition(-1, -1, -1); IndexPosition cIndex, bIndex; Chunk chunk; // Add start Terrain.GetLocalBlockCoords(startGlobalPosition, out cIndex, out bIndex); if (OwnerPlayer.NumBlocks > 0 && World.Terrain.Chunks.TryGetValue(cIndex, out chunk)) { if (IsBlockPlacementSafe(bIndex, cIndex)) { Block block = new Block(Block.CUSTOM.Data, BlockColor.R, BlockColor.G, BlockColor.B); OwnerPlayer.NumBlocks--; if (!GlobalNetwork.IsConnected) { chunk.SetBlock(block, bIndex); } else { World.SetBlock(chunk.IndexPosition, bIndex, block, true); } } } // Add middle for (int _i = 0; _i < 1000; _i++) { if (OwnerPlayer.NumBlocks <= 0) { break; } float i = _i / 1000f; Vector3 worldPos = ray.Origin + ray.Direction * i; IndexPosition globalIndex = new IndexPosition( (int)(worldPos.X / Block.CUBE_SIZE), (int)(worldPos.Y / Block.CUBE_SIZE), (int)(worldPos.Z / Block.CUBE_SIZE)); Terrain.GetLocalBlockCoords(globalIndex, out cIndex, out bIndex); if (cIndex == lastCIndex && bIndex == lastBIndex || globalIndex == startGlobalPosition || globalIndex == endGlobalPosition) { continue; } lastCIndex = cIndex; lastBIndex = bIndex; if (World.Terrain.Chunks.TryGetValue(cIndex, out chunk)) { if (IsBlockPlacementSafe(bIndex, cIndex)) { Block block = new Block(Block.CUSTOM.Data, BlockColor.R, BlockColor.G, BlockColor.B); OwnerPlayer.NumBlocks--; if (!GlobalNetwork.IsConnected) { chunk.SetBlock(block, bIndex); } else { World.SetBlock(chunk.IndexPosition, bIndex, block, true); } } } } // Add end Terrain.GetLocalBlockCoords(endGlobalPosition, out cIndex, out bIndex); if (OwnerPlayer.NumBlocks > 0 && World.Terrain.Chunks.TryGetValue(cIndex, out chunk)) { if (IsBlockPlacementSafe(bIndex, cIndex)) { Block block = new Block(Block.CUSTOM.Data, BlockColor.R, BlockColor.G, BlockColor.B); OwnerPlayer.NumBlocks--; if (!GlobalNetwork.IsConnected) { chunk.SetBlock(block, bIndex); } else { World.SetBlock(chunk.IndexPosition, bIndex, block, true); } } } }
protected override void Update(float deltaTime) { if (GlobalNetwork.IsClient) { if (Input.GetControlDown("PickColor")) { PickColor(); } int ocx = ColorX, ocy = ColorY; if (Input.GetKeyDown(Key.Up) && ColorY > 0) { ColorY--; } if (Input.GetKeyDown(Key.Down) && ColorY < (PaletteHeight - 1)) { ColorY++; } if (Input.GetKeyDown(Key.Left) && ColorX > 0) { ColorX--; } if (Input.GetKeyDown(Key.Right) && ColorX < (PaletteWidth - 1)) { ColorX++; } if (ocx != ColorX || ocy != ColorY) { BlockColor = Colors[ColorY, ColorX]; } TerrainRaycastResult result = World.TerrainPhysics.Raycast( new Ray(Camera.Position, Camera.ViewMatrix.Forward()), true, PLACE_RANGE); if (result.Intersects) { IndexPosition ipos = ShiftIPos(result.BlockIndex.Value, result.IntersectionCubeSide.Value); IndexPosition newChunkPos; Chunk.WrapBlockCoords(ipos.X, ipos.Y, ipos.Z, result.Chunk.IndexPosition, out ipos, out newChunkPos); globalMousePosition = Terrain.GetGlobalBlockCoords(newChunkPos, ipos); mouseOverBlock = true; } else { mouseOverBlock = false; } if (holdingDown) { if (mouseOverBlock) { endGlobalPosition = globalMousePosition; } if (Input.GetControlUp("SecondaryFire")) { holdingDown = false; primaryCooldown = Config.PrimaryFireDelay; if (mouseOverBlock) { buildAudioSource?.Play(); Vector3 startWorld = startGlobalPosition * Block.CUBE_3D_SIZE; Vector3 endWorld = endGlobalPosition * Block.CUBE_3D_SIZE; Ray ray = new Ray(startWorld, endWorld - startWorld); RayPlace(ray); } } } } base.Update(deltaTime); }
public override void OnInspectorGUI() { MeshTreeBase meshTreeBase = target as MeshTreeBase; if (meshTreeBase.IsBuilding()) { GUI.enabled = false; } DrawDefaultInspector(); if (meshTreeBase is MeshTree) { MeshTree meshTree = meshTreeBase as MeshTree; Object meshObject = EditorGUILayout.ObjectField(meshTree.srcMesh is Mesh ? "Mesh" : "Root Object", meshTree.srcMesh, typeof(Object), true); if (meshObject != meshTree.srcMesh && meshObject is GameObject && Event.current.command) { MeshFilter meshFilter = ((GameObject)meshObject).GetComponent <MeshFilter>(); if (meshFilter != null && meshFilter.sharedMesh != null) { meshObject = meshFilter.sharedMesh; } } if (meshObject != meshTree.srcMesh) { Undo.RegisterCompleteObjectUndo(meshTree, "Inspector"); meshTree.srcMesh = meshObject; EditorUtility.SetDirty(meshTree); } if (meshObject is GameObject) { PrefabType prefabType = PrefabUtility.GetPrefabType(meshObject); if (prefabType != PrefabType.Prefab && prefabType != PrefabType.ModelPrefab) { if (m_errorStyle == null) { m_errorStyle = new GUIStyle(); m_errorStyle.richText = true; m_errorStyle.wordWrap = true; } GUILayout.TextArea("<color=red>A reference to a scene object will not be serialized in Asset data. You will need to set the root object again when you rebuild the tree. Use a prefab instead.</color>", m_errorStyle); } EditorGUILayout.PropertyField(serializedObject.FindProperty("m_layerMask")); SerializedProperty excludeRenderTypes = serializedObject.FindProperty("m_excludeRenderTypes"); excludeRenderTypes.isExpanded = EditorGUILayout.Foldout(excludeRenderTypes.isExpanded, "Exclude Render Types"); if (excludeRenderTypes.isExpanded) { for (int i = 0; i < excludeRenderTypes.arraySize + 1; ++i) { string renderType; if (m_editingRenderType == i) { renderType = m_editingString; } else if (i < excludeRenderTypes.arraySize) { renderType = excludeRenderTypes.GetArrayElementAtIndex(i).stringValue; } else { renderType = ""; } string controlName = "RenderType" + i.ToString(); GUI.SetNextControlName(controlName); string newRenderType = EditorGUILayout.TextField(renderType); string focusedControl = GUI.GetNameOfFocusedControl(); if (m_editingRenderType == i) { m_editingString = newRenderType; if (focusedControl != controlName || (/*Event.current.isKey &&*/ (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter))) { ApplyEditingRenderType(); } else if (/*Event.current.isKey &&*/ Event.current.keyCode == KeyCode.Escape) { CancelEditingRenderType(); } } else if (renderType != newRenderType) { ApplyEditingRenderType(); m_editingRenderType = i; m_editingString = newRenderType; } } } EditorGUILayout.PropertyField(serializedObject.FindProperty("m_scaledOffset")); EditorGUILayout.PropertyField(serializedObject.FindProperty("m_fixedOffset")); serializedObject.ApplyModifiedProperties(); } } if (meshTreeBase is TerrainMeshTree) { TerrainMeshTree terrainMeshTree = meshTreeBase as TerrainMeshTree; Object terrainObj = EditorGUILayout.ObjectField("Terrain Data", terrainMeshTree.terrainData, typeof(Object), true); if (terrainObj != terrainMeshTree.terrainData) { TerrainData terrainData = terrainObj as TerrainData; if (terrainData == null && terrainObj is GameObject) { Terrain terrain = ((GameObject)terrainObj).GetComponent <Terrain>(); if (terrain != null) { terrainData = terrain.terrainData; } } if (terrainData != null || terrainObj == null) { terrainMeshTree.terrainData = terrainData; } } } if (meshTreeBase.IsBuilding()) { GUI.enabled = true; m_isBuilding = true; EditorGUILayout.LabelField("Building... " + Mathf.FloorToInt(100 * meshTreeBase.GetBuildProgress()).ToString() + "%"); } else { GUI.enabled = meshTreeBase.IsReadyToBuild(); if (m_isBuilding) { m_isBuilding = false; m_memoryUsage = meshTreeBase.GetMemoryUsage(); EditorUtility.SetDirty(meshTreeBase); } if (meshTreeBase.IsPrebuilt()) { m_showBuiltData = EditorGUILayout.Foldout(m_showBuiltData, "Built Tree Info"); if (m_showBuiltData) { string memorySize; float mb = m_memoryUsage / (1024.0f * 1024.0f); if (1.0f <= mb) { memorySize = mb.ToString("f3") + "MB"; } else { float kb = m_memoryUsage / 1024.0f; memorySize = kb.ToString("f3") + "KB"; } EditorGUILayout.LabelField("Memory", memorySize); EditorGUILayout.LabelField("Node Count", meshTreeBase.GetNodeCount().ToString()); } } if (GUILayout.Button(meshTreeBase.IsPrebuilt() ? "Rebuild" : "Build")) { ApplyEditingRenderType(); m_isBuilding = true; BuildMeshTree(meshTreeBase); } } GUI.enabled = true; }
void EnemyBreed() { float randomValue = Random.value; if (attributes.libido >= 200 && randomValue < 0.5) { GameObject activeCreature = GameObject.Find("Enemies" + globalAttributes.indice + "/" + character).gameObject; Vector3 childPosition = new Vector3(); Vector3 childRotation; Vector3 childScale; childPosition.x = activeCreature.transform.position.x + 7; // childPosition.z = activeCreature.transform.position.z + 7; // childRotation.x = 0; childRotation.y = 0; childRotation.z = 0; childScale.x = 5; childScale.y = 5; childScale.z = 1; GameObject creaturesNode = GameObject.Find("EnemiesCreatures/Enemies" + globalAttributes.indice + "/"); int lastCreatureName = int.Parse(creaturesNode.transform.GetChild(creaturesNode.transform.childCount - 1).name); GameObject childObject = new GameObject((lastCreatureName + 1).ToString()); SpriteRenderer spriteRenderer = childObject.AddComponent <SpriteRenderer>(); Animator childAnimator = childObject.AddComponent <Animator>(); childAnimator.runtimeAnimatorController = Resources.Load("playerSpeciesController") as RuntimeAnimatorController; childAnimator.updateMode = AnimatorUpdateMode.Normal; childAnimator.cullingMode = AnimatorCullingMode.AlwaysAnimate; childAnimator.SetInteger("movementUpgrade", attributes.movementUpgrade); childAnimator.SetInteger("perceptionUpgrade", attributes.perceptionUpgrade); childAnimator.SetInteger("combatUpgrade", Mathf.Max(attributes.attackUpgrade, attributes.deffenseUpgrade)); childObject.transform.parent = GameObject.Find("EnemiesCreatures/Enemies" + globalAttributes.indice + "/").transform; childObject.transform.rotation = Quaternion.Euler(childRotation); childObject.transform.localScale = childScale; BoxCollider childBox = childObject.AddComponent <BoxCollider>(); childBox.isTrigger = false; childBox.material = new PhysicMaterial("None"); Vector3 childBoxCenter; childBoxCenter.x = 0; childBoxCenter.y = 0; childBoxCenter.z = 0; childBox.center = childBoxCenter; Vector3 childBoxSize; childBoxSize.x = 0.9f; childBoxSize.y = 0.8f; childBoxSize.z = 4; childBox.size = childBoxSize; Rigidbody childRigidbody = childObject.AddComponent <Rigidbody>(); childRigidbody.mass = 10; childRigidbody.drag = 0; childRigidbody.useGravity = true; childRigidbody.isKinematic = false; childRigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete; childRigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; childObject.tag = "EnemySpecies"; Terrain terrain = GameObject.Find("Terrain").GetComponent <Terrain>(); childPosition.y = terrain.SampleHeight(childPosition) + 40; childObject.transform.position = childPosition; childObject.transform.parent.gameObject.GetComponent <EnemiesGlobalAttributes>(); EnemiesAttributes childAttributes = childObject.AddComponent <EnemiesAttributes>(); childAttributes.movementUpgrade = attributes.movementUpgrade; childAttributes.perceptionUpgrade = attributes.perceptionUpgrade; childAttributes.attackUpgrade = attributes.attackUpgrade; childAttributes.deffenseUpgrade = attributes.deffenseUpgrade; NavMeshObstacle obstacleC = childObject.AddComponent <NavMeshObstacle>(); obstacleC.center = new Vector3(0f, 0f, 0f); obstacleC.size = new Vector3(1f, 1f, 4.1f); obstacleC.carving = true; obstacleC.enabled = true; NavMeshAgent agentC = childObject.AddComponent <NavMeshAgent>(); agentC.radius = 0.53f; agentC.height = 1; agentC.speed = (6.0f + childAttributes.movementUpgrade * 3) * GameConstants.movementSpeed; agentC.angularSpeed = 120; agentC.acceleration = 99; agentC.stoppingDistance = 0; agentC.autoBraking = true; agentC.avoidancePriority = 50; agentC.autoTraverseOffMeshLink = true; agentC.autoRepath = true; agentC.areaMask = 1; agentC.enabled = false; Debug.Log("Enemy newborn generated:\nIndice - " + globalAttributes.indice + "\nSpecies - " + species + ";\nPersona - " + persona.Nome + ";"); childObject.AddComponent <EnemiesAttributeUpdater>(); childObject.AddComponent <EnemiesCharacterMovement>(); childObject.AddComponent <FixRotation>(); childObject.AddComponent <EnemiesAutonomousBehavior>(); attributes.libido = 0; } }
public static float TerrainValue(Terrain terrain, Vector3 pos) { // use information from a manager/god-class return(terrain.SampleHeight(pos)); }
bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain terrain) { var terrainLayers = terrain.terrainData.terrainLayers; if (!DoesTerrainUseMaskMaps(terrainLayers)) { return(false); } // Don't use the member field enableHeightBlend as ShaderGUI.OnGUI might not be called if the material UI is folded. bool heightBlend = terrain.materialTemplate.HasProperty(kEnableHeightBlend) && terrain.materialTemplate.GetFloat(kEnableHeightBlend) > 0; terrainLayer.diffuseTexture = EditorGUILayout.ObjectField(styles.diffuseTexture, terrainLayer.diffuseTexture, typeof(Texture2D), false) as Texture2D; TerrainLayerUtility.ValidateDiffuseTextureUI(terrainLayer.diffuseTexture); var diffuseRemapMin = terrainLayer.diffuseRemapMin; var diffuseRemapMax = terrainLayer.diffuseRemapMax; EditorGUI.BeginChangeCheck(); bool enableDensity = false; if (terrainLayer.diffuseTexture != null) { var rect = GUILayoutUtility.GetLastRect(); rect.y += 16 + 4; rect.width = EditorGUIUtility.labelWidth + 64; rect.height = 16; ++EditorGUI.indentLevel; var diffuseTint = new Color(diffuseRemapMax.x, diffuseRemapMax.y, diffuseRemapMax.z); diffuseTint = EditorGUI.ColorField(rect, styles.colorTint, diffuseTint, true, false, false); diffuseRemapMax.x = diffuseTint.r; diffuseRemapMax.y = diffuseTint.g; diffuseRemapMax.z = diffuseTint.b; diffuseRemapMin.x = diffuseRemapMin.y = diffuseRemapMin.z = 0; if (!heightBlend) { rect.y = rect.yMax + 2; enableDensity = EditorGUI.Toggle(rect, styles.opacityAsDensity, diffuseRemapMin.w > 0); } --EditorGUI.indentLevel; } diffuseRemapMax.w = 1; diffuseRemapMin.w = enableDensity ? 1 : 0; if (EditorGUI.EndChangeCheck()) { terrainLayer.diffuseRemapMin = diffuseRemapMin; terrainLayer.diffuseRemapMax = diffuseRemapMax; } terrainLayer.normalMapTexture = EditorGUILayout.ObjectField(styles.normalMapTexture, terrainLayer.normalMapTexture, typeof(Texture2D), false) as Texture2D; TerrainLayerUtility.ValidateNormalMapTextureUI(terrainLayer.normalMapTexture, TerrainLayerUtility.CheckNormalMapTextureType(terrainLayer.normalMapTexture)); if (terrainLayer.normalMapTexture != null) { var rect = GUILayoutUtility.GetLastRect(); rect.y += 16 + 4; rect.width = EditorGUIUtility.labelWidth + 64; rect.height = 16; ++EditorGUI.indentLevel; terrainLayer.normalScale = EditorGUI.FloatField(rect, styles.normalScale, terrainLayer.normalScale); --EditorGUI.indentLevel; } terrainLayer.maskMapTexture = EditorGUILayout.ObjectField(heightBlend ? styles.maskMapTexture : styles.maskMapTextureWithoutHeight, terrainLayer.maskMapTexture, typeof(Texture2D), false) as Texture2D; TerrainLayerUtility.ValidateMaskMapTextureUI(terrainLayer.maskMapTexture); var maskMapRemapMin = terrainLayer.maskMapRemapMin; var maskMapRemapMax = terrainLayer.maskMapRemapMax; ++EditorGUI.indentLevel; EditorGUI.BeginChangeCheck(); m_ShowChannelRemapping = EditorGUILayout.Foldout(m_ShowChannelRemapping, terrainLayer.maskMapTexture != null ? s_Styles.channelRemapping : s_Styles.defaultValues); if (m_ShowChannelRemapping) { if (terrainLayer.maskMapTexture != null) { float min, max; min = maskMapRemapMin.x; max = maskMapRemapMax.x; EditorGUILayout.MinMaxSlider(s_Styles.metallic, ref min, ref max, 0, 1); maskMapRemapMin.x = min; maskMapRemapMax.x = max; min = maskMapRemapMin.y; max = maskMapRemapMax.y; EditorGUILayout.MinMaxSlider(s_Styles.ao, ref min, ref max, 0, 1); maskMapRemapMin.y = min; maskMapRemapMax.y = max; if (heightBlend) { EditorGUILayout.LabelField(styles.height); ++EditorGUI.indentLevel; m_HeightParametrization = (HeightParametrization)EditorGUILayout.EnumPopup(styles.heightParametrization, m_HeightParametrization); if (m_HeightParametrization == HeightParametrization.Amplitude) { // (height - heightBase) * amplitude float amplitude = Mathf.Max(maskMapRemapMax.z - maskMapRemapMin.z, Mathf.Epsilon); // to avoid divide by zero float heightBase = -maskMapRemapMin.z / amplitude; amplitude = EditorGUILayout.FloatField(styles.heightAmplitude, amplitude * 100) / 100; heightBase = EditorGUILayout.FloatField(styles.heightBase, heightBase); maskMapRemapMin.z = -heightBase * amplitude; maskMapRemapMax.z = (1 - heightBase) * amplitude; } else { maskMapRemapMin.z = EditorGUILayout.FloatField(styles.heightMin, maskMapRemapMin.z * 100) / 100; maskMapRemapMax.z = EditorGUILayout.FloatField(styles.heightMax, maskMapRemapMax.z * 100) / 100; } --EditorGUI.indentLevel; } min = maskMapRemapMin.w; max = maskMapRemapMax.w; EditorGUILayout.MinMaxSlider(s_Styles.smoothness, ref min, ref max, 0, 1); maskMapRemapMin.w = min; maskMapRemapMax.w = max; } else { maskMapRemapMin.x = maskMapRemapMax.x = EditorGUILayout.Slider(s_Styles.metallic, maskMapRemapMin.x, 0, 1); maskMapRemapMin.y = maskMapRemapMax.y = EditorGUILayout.Slider(s_Styles.ao, maskMapRemapMin.y, 0, 1); if (heightBlend) { maskMapRemapMin.z = maskMapRemapMax.z = EditorGUILayout.FloatField(s_Styles.heightCm, maskMapRemapMin.z * 100) / 100; } maskMapRemapMin.w = maskMapRemapMax.w = EditorGUILayout.Slider(s_Styles.smoothness, maskMapRemapMin.w, 0, 1); } } if (EditorGUI.EndChangeCheck()) { terrainLayer.maskMapRemapMin = maskMapRemapMin; terrainLayer.maskMapRemapMax = maskMapRemapMax; } --EditorGUI.indentLevel; EditorGUILayout.Space(); TerrainLayerUtility.TilingSettingsUI(terrainLayer); return(true); }
public void GivenTestInputTerrainAtPositionIsCorrect(string path, int x, int y, Terrain expectedTerrain) { var map = new Map(); map.ReadFile(path); map.X(x); map.Y(y); Assert.Equal(expectedTerrain, map.TerrainAtPosition()); }
void CreateTerrain() { //fire up the progress bar ShowProgressBar(1, 100); TerrainData terrain = new TerrainData(); terrain.heightmapResolution = resolution; GameObject terrainObject = Terrain.CreateTerrainGameObject(terrain); Undo.RegisterCreatedObjectUndo(terrainObject, "Object to Terrain"); MeshCollider collider = Selection.activeGameObject.GetComponent <MeshCollider>(); CleanUp cleanUp = null; //Add a collider to our source object if it does not exist. //Otherwise raycasting doesn't work. if (!collider) { collider = Selection.activeGameObject.AddComponent <MeshCollider>(); cleanUp = () => DestroyImmediate(collider); } Bounds bounds = collider.bounds; float sizeFactor = collider.bounds.size.y / (collider.bounds.size.y + addTerrain.y); terrain.size = collider.bounds.size + addTerrain; bounds.size = new Vector3(terrain.size.x, collider.bounds.size.y, terrain.size.z); // Do raycasting samples over the object to see what terrain heights should be float[,] heights = new float[terrain.heightmapWidth, terrain.heightmapHeight]; Ray ray = new Ray(new Vector3(bounds.min.x, bounds.max.y + bounds.size.y, bounds.min.z), -Vector3.up); RaycastHit hit = new RaycastHit(); float meshHeightInverse = 1 / bounds.size.y; Vector3 rayOrigin = ray.origin; int maxHeight = heights.GetLength(0); int maxLength = heights.GetLength(1); Vector2 stepXZ = new Vector2(bounds.size.x / maxLength, bounds.size.z / maxHeight); for (int zCount = 0; zCount < maxHeight; zCount++) { ShowProgressBar(zCount, maxHeight); for (int xCount = 0; xCount < maxLength; xCount++) { float height = 0.0f; if (collider.Raycast(ray, out hit, bounds.size.y * 3)) { height = (hit.point.y - bounds.min.y) * meshHeightInverse; height += shiftHeight; //bottom up if (bottomTopRadioSelected == 0) { height *= sizeFactor; } //clamp if (height < 0) { height = 0; } } heights[zCount, xCount] = height; rayOrigin.x += stepXZ[0]; ray.origin = rayOrigin; } rayOrigin.z += stepXZ[1]; rayOrigin.x = bounds.min.x; ray.origin = rayOrigin; } terrain.SetHeights(0, 0, heights); EditorUtility.ClearProgressBar(); if (cleanUp != null) { cleanUp(); } }
public static void Process(Terrain terrain) { // Get a reference to the terrain data TerrainData terrainData = terrain.terrainData; // Splatmap data is stored internally as a 3d array of floats, so declare a new empty array ready for your custom splatmap data: float[, ,] splatmapData = new float[terrainData.alphamapWidth, terrainData.alphamapHeight, terrainData.alphamapLayers]; for (int y = 0; y < terrainData.alphamapHeight; y++) { for (int x = 0; x < terrainData.alphamapWidth; x++) { // Normalise x/y coordinates to range 0-1 float y_01 = (float)y / (float)terrainData.alphamapHeight; float x_01 = (float)x / (float)terrainData.alphamapWidth; // Sample the height at this location (note GetHeight expects int coordinates corresponding to locations in the heightmap array) float height = terrainData.GetHeight(Mathf.RoundToInt(y_01 * terrainData.heightmapHeight), Mathf.RoundToInt(x_01 * terrainData.heightmapWidth)); // Calculate the normal of the terrain (note this is in normalised coordinates relative to the overall terrain dimensions) Vector3 normal = terrainData.GetInterpolatedNormal(y_01, x_01); // Calculate the steepness of the terrain float steepness = terrainData.GetSteepness(y_01, x_01); // Setup an array to record the mix of texture weights at this point float[] splatWeights = new float[terrainData.alphamapLayers]; // CHANGE THE RULES BELOW TO SET THE WEIGHTS OF EACH TEXTURE ON WHATEVER RULES YOU WANT // Texture[0] has constant influence splatWeights[0] = 0.5f; // Texture[1] is stronger at lower altitudes splatWeights[1] = Mathf.Clamp01((terrainData.heightmapHeight - height)); // Texture[2] stronger on flatter terrain // Note "steepness" is unbounded, so we "normalise" it by dividing by the extent of heightmap height and scale factor // Subtract result from 1.0 to give greater weighting to flat surfaces splatWeights[2] = 1.0f - Mathf.Clamp01(steepness * steepness / (terrainData.heightmapHeight / 5.0f)); // Texture[3] increases with height but only on surfaces facing positive Z axis splatWeights[3] = height * Mathf.Clamp01(normal.z); // Sum of all textures weights must add to 1, so calculate normalization factor from sum of weights float z = splatWeights.Sum(); // Loop through each terrain texture for (int i = 0; i < terrainData.alphamapLayers; i++) { // Normalize so that sum of all texture weights = 1 splatWeights[i] /= z; // Assign this point to the splatmap array splatmapData[x, y, i] = splatWeights[i]; } } } // Finally assign the new splatmap to the terrainData: terrainData.SetAlphamaps(0, 0, splatmapData); }
public static Terrain ClearFlags(this Terrain value, Terrain flags) { return(value.SetFlags(flags, false)); }
/// <summary> /// Setup for the automatically probe spawning /// </summary> /// <param name="profile"></param> public static void CreateAutomaticProbes(AmbientLightingProfile profile, AmbientSkiesConsts.RenderPipelineSettings renderPipelineSettings) { GameObject oldReflectionProbe = GameObject.Find("Global Reflection Probe"); if (oldReflectionProbe != null) { Object.DestroyImmediate(oldReflectionProbe); Debug.Log("Old Reflection Probe Destroyed"); } GameObject relfectionParentObject = ReflectionProbeParenting(true); int numberTerrains = Terrain.activeTerrains.Length; if (numberTerrains == 0) { Debug.LogError("Unable to initiate probe spawning systen. No terrain found"); return; } else { if (profile.reflectionProbesPerRow < 2) { Debug.LogError("Please set Probes Per Row to a value of 2 or higher"); return; } else { m_currentProbeCount = 0; float seaLevel = 0f; bool seaLevelActive = false; #if GAIA_PRESENT Gaia.GaiaSessionManager gaiaSession = Object.FindObjectOfType <Gaia.GaiaSessionManager>(); if (gaiaSession != null) { seaLevel = profile.seaLevel; seaLevelActive = true; } #else seaLevel = profile.seaLevel; #endif for (int terrainIdx = 0; terrainIdx < numberTerrains; terrainIdx++) { Terrain terrain = Terrain.activeTerrains[terrainIdx]; Vector3 terrainSize = terrain.terrainData.size; for (int row = 0; row < profile.reflectionProbesPerRow; ++row) { for (int columns = 0; columns < profile.reflectionProbesPerRow; ++columns) { GameObject probeObject = new GameObject("Global Generated Reflection Probe"); Vector3 newPosition = probeObject.transform.position; newPosition.x = ((columns + 1) * terrainSize.x / profile.reflectionProbesPerRow) - terrainSize.x / profile.reflectionProbesPerRow / 2f + terrain.transform.position.x; newPosition.z = ((row + 1) * terrainSize.z / profile.reflectionProbesPerRow) - terrainSize.z / profile.reflectionProbesPerRow / 2f + terrain.transform.position.z; float sampledHeight = terrain.SampleHeight(newPosition); ReflectionProbe probeData = probeObject.AddComponent <ReflectionProbe>(); probeData.enabled = false; probeData.blendDistance = 0f; probeData.cullingMask = profile.reflectionprobeCullingMask; probeData.farClipPlane = profile.reflectionProbeClipPlaneDistance; probeData.mode = profile.reflectionProbeMode; probeData.refreshMode = profile.reflectionProbeRefresh; if (seaLevelActive) { newPosition.y = 500f + seaLevel + 0.2f; } else { newPosition.y = sampledHeight + profile.reflectionProbeOffset; probeData.center = new Vector3(0f, 0f - profile.reflectionProbeOffset - sampledHeight, 0f); } probeObject.transform.position = newPosition; probeObject.transform.SetParent(relfectionParentObject.transform); switch (profile.reflectionProbeResolution) { case AmbientSkiesConsts.ReflectionProbeResolution.Resolution16: probeData.resolution = 16; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution32: probeData.resolution = 32; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution64: probeData.resolution = 64; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution128: probeData.resolution = 128; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution256: probeData.resolution = 256; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution512: probeData.resolution = 512; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution1024: probeData.resolution = 1024; break; case AmbientSkiesConsts.ReflectionProbeResolution.Resolution2048: probeData.resolution = 2048; break; } probeData.shadowDistance = 80f; probeData.size = new Vector3(terrainSize.x / profile.reflectionProbesPerRow, terrainSize.y, terrainSize.z / profile.reflectionProbesPerRow); probeData.timeSlicingMode = profile.reflectionProbeTimeSlicingMode; probeData.hdr = true; probeData.shadowDistance = profile.reflectionProbeShadowDistance; //If HDRP if (renderPipelineSettings == AmbientSkiesConsts.RenderPipelineSettings.HighDefinition) { #if HDPipeline && UNITY_2018_3_OR_NEWER HDAdditionalReflectionData reflectionData = probeObject.GetComponent <HDAdditionalReflectionData>(); if (reflectionData == null) { reflectionData = probeObject.AddComponent <HDAdditionalReflectionData>(); reflectionData.multiplier = 1f; } else { reflectionData.multiplier = 1f; } #endif } m_storedProbes.Add(probeData); m_currentProbeCount++; } } } #if HDPipeline && GAIA_PRESENT if (seaLevelActive) { GameObject planarObject = GameObject.Find("Gaia Water Planar Reflections Object"); if (planarObject == null) { planarObject = new GameObject("Gaia Water Planar Reflections Object"); PlanarReflectionProbe planar = planarObject.AddComponent <PlanarReflectionProbe>(); planar.mode = ProbeSettings.Mode.Realtime; planar.realtimeMode = ProbeSettings.RealtimeMode.OnEnable; planar.influenceVolume.shape = InfluenceShape.Box; planar.influenceVolume.boxSize = new Vector3(10000f, 5f, 10000f); planarObject.transform.position = new Vector3(0f, profile.seaLevel + 0.2f, 0f); planarObject.transform.SetParent(relfectionParentObject.transform); } } #endif m_probeRenderActive = true; } } }
// Use this for initialization void Start() { terrain = Terrain.activeTerrain; terrainData = terrain.terrainData; terrainPos = terrain.transform.position; }
public static Terrain SetFlags(this Terrain value, Terrain flags) { return(value.SetFlags(flags, true)); }
internal static void RemoveTerrainLayer(Terrain terrain, int index) { var terrainData = terrain.terrainData; Undo.RegisterCompleteObjectUndo(terrainData, "Remove terrain layer"); int width = terrainData.alphamapWidth; int height = terrainData.alphamapHeight; float[,,] alphamap = terrainData.GetAlphamaps(0, 0, width, height); int alphaCount = alphamap.GetLength(2); int newAlphaCount = alphaCount - 1; float[,,] newalphamap = new float[height, width, newAlphaCount]; // move further alphamaps one index below for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { for (int a = 0; a < index; ++a) { newalphamap[y, x, a] = alphamap[y, x, a]; } for (int a = index + 1; a < alphaCount; ++a) { newalphamap[y, x, a - 1] = alphamap[y, x, a]; } } } // normalize weights in new alpha map for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { float sum = 0.0F; for (int a = 0; a < newAlphaCount; ++a) { sum += newalphamap[y, x, a]; } if (sum >= 0.01) { float multiplier = 1.0F / sum; for (int a = 0; a < newAlphaCount; ++a) { newalphamap[y, x, a] *= multiplier; } } else { // in case all weights sum to pretty much zero (e.g. // removing splat that had 100% weight), assign // everything to 1st splat texture (just like // initial terrain). for (int a = 0; a < newAlphaCount; ++a) { newalphamap[y, x, a] = (a == 0) ? 1.0f : 0.0f; } } } } // remove splat from terrain prototypes var layers = terrainData.terrainLayers; var newSplats = new TerrainLayer[layers.Length - 1]; for (int a = 0; a < index; ++a) { newSplats[a] = layers[a]; } for (int a = index + 1; a < alphaCount; ++a) { newSplats[a - 1] = layers[a]; } terrainData.terrainLayers = newSplats; // set new alphamaps terrainData.SetAlphamaps(0, 0, newalphamap); }