public override void PlaceTile(TownManager tm, Map map, List <Tile> buildingTiles, int rotAmt, Vector2 curBuildRotScale) { ResourceTile rT = buildingTiles[0] as ResourceTile; rotatedScale = curBuildRotScale; CollectResourceBuildingTile bMain = new CollectResourceBuildingTile(buildingTiles[0].GetMapLoc(), buildingTiles[0].GetWorldLoc(), 'B', buildingTiles[0].GetTileObj(), this, rT.GetIsTrees()); bMain.mapScript = map; bMain.tm = tm; Vector2 tileMapPos = buildingTiles[0].GetMapLoc(); List <WorldResource> resources = rT.GetResourcesList(); map.SetTileFromMapPos((int)tileMapPos.x, (int)tileMapPos.y, bMain); bMain.SetResourcesLeft(resources.Count); for (int i = 0; i < resources.Count; i++) { // Create a task for each tree and send it to the town manager citizenTasks list Queue <Target> taskQ = new Queue <Target>(); Vector3 loc = resources[i].GetResourceObject().transform.position; taskQ.Enqueue(new Target(loc, bMain, resources[i], null, 4f, false, true)); taskQ.Enqueue(new Target(new Vector3(0, 0, 0), false)); Task t = new Task(taskQ, true); tm.AddTask(t); } }
public IEnumerator goFish() { Debug.Log("Grid " + grid); Debug.Log("ResourceTiles " + grid.resourceTiles.Count); ResourceTile mostTile = grid.resourceTiles.ElementAt(UnityEngine.Random.Range(0, grid.resourceTiles.Count)).Value; int stagger = UnityEngine.Random.Range(5, 30); for (int i = 0; i < stagger; i++) { yield return(null); } yield return(StartCoroutine(moveBoat(mostTile.tileIndex()))); mostTile.isHere(gameObject); //fish(mostTile.tileIndex()); mostTile.fishingHere(gameObject); yield return(null); entCatch = mostTile.getFish(gameObject); yield return(null); mostTile.leftHere(gameObject); }
public UndoCopyPaste(CPos cell, TerrainTile mapTile, ResourceTile resourceTile, byte height) { Cell = cell; MapTile = mapTile; ResourceTile = resourceTile; Height = height; }
// Use this for initialization void Start() { building = Controller.whatWasClicked.GetComponent <ResourceTile>(); buildCost = Controller.whatWasClicked.GetComponent <BuildingCosts>(); buildingName = building.whatBuildingIsThis; buildingInfo = buildingName + " (LV." + building.WhatLevel + ")"; currStats = "This " + buildingName + " produces " + building.IndividualOutput.ToString() + " " + building.whatResource.ToString() + "."; if (building.nextBuilding != null) { nextStats = "Upgraded, this " + buildingName + " will produce " + (building.nextBuilding.GetComponent <ResourceTile>().IndividualOutput).ToString() + " " + building.whatResource.ToString() + "."; } else { nextStats = "This " + buildingName + " is fully upgraded."; } cost = "To upgrade this " + buildingName + " you will need:\n" + buildCost.UFoodCost + " Food\n" + buildCost.UWoodCost + " Wood\n" + buildCost.UStoneCost + " Stone\n" + buildCost.UMetalCost + " Metal"; }
public IEnumerator goFish() { ResourceTile mostTile = grid.resourceTiles.ElementAt(UnityEngine.Random.Range(0, grid.resourceTiles.Count)).Value; int stagger = UnityEngine.Random.Range(5, 30); for (int i = 0; i < stagger; i++) { yield return(null); } yield return(StartCoroutine(moveBoat(mostTile.tileIndex()))); mostTile.isHere(gameObject); //fish(mostTile.tileIndex()); mostTile.fishingHere(gameObject); yield return(null); mostTile.getFish(gameObject); currentGrossProfit = currentCatch * fishPrice; currentProfit = currentCatch * fishPrice - costs; yield return(null); mostTile.leftHere(gameObject); }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return ( (tile.baseCoverType == BaseCoverType.Barren) || (tile.baseCoverType == BaseCoverType.Developed && tile.zoneType != ZoneType.Residential) ); }
void fish(Vector3Int tileIndex) { ResourceTile tile = grid.getTileAt(tileIndex.x, tileIndex.y); // currentCatch = tile.extract(capacity * efficiency) *15; monthlyCatch += currentCatch; yearCatch += currentCatch; }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return !( tile.zoneType != ZoneType.None || tile.housingCapacity > 0 || tile.housingOccupants > 0 ); }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return ( tile.can_be_surveyed && !tile.survey_requested && !tile.is_surveyed ); }
public override void initCached(BaseAgentBehavior owner) { base.initCached(owner); tile = owner.entities.getEntity <Destination>().getComponent <Destination>().destination; currentCatch = owner.entities.getEntity <Catch>(); }
public void CreateMapFromTiles(TempTile[] tempTiles) { Tile[] newTiles = new Tile[tempTiles.Length]; for (int x = 0; x < mapWidth; x++) { for (int y = 0; y < mapHeight; y++) { TempTile tile = tempTiles[(mapWidth * y) + x]; Vector2 worldLoc2 = GetTileWorldLoc(tile); Vector3 worldLoc3 = new Vector3(worldLoc2.x, 0, worldLoc2.y); Vector3 tilePos = new Vector3(worldLoc2.x + 0.5f, 0, worldLoc2.y + 0.5f); int rotateAmt = Random.Range(0, 4); Quaternion tileRot = Quaternion.Euler(0, 90 * rotateAmt, 0); char tileType = tile.type; int tileAutoID = tile.autotileID; if ((tileType == 'F' || tileType == 'R') && tileAutoID == 15) // Forest Biome { GameObject tileObj = (GameObject)Instantiate(grassTiles[0], tilePos, tileRot); tileObj.transform.parent = transform; List <WorldResource> tileResources = GenerateResources(tile, worldLoc2, (tileType == 'F')); ResourceTile rT = new ResourceTile(tile.loc, worldLoc3, 'R', tileObj, tileResources, (tileType == 'F')); newTiles[(mapWidth * y) + x] = rT; } else if (tileAutoID > -1) // Grass and Coast Biome { if (tileAutoID == 15) { float flowerPercent = Random.Range(0f, (float)grassTiles.Length); int tileNum = 0; if (flowerPercent < flowerCutoff) { tileNum = 1; } GameObject tileObj = (GameObject)Instantiate(grassTiles[tileNum], tilePos, tileRot); tileObj.transform.parent = transform; GrassTile gT = new GrassTile(tile.loc, worldLoc3, 'G', tileObj); newTiles[(mapWidth * y) + x] = gT; } else // Ocean Biome { GameObject tileObj = (GameObject)Instantiate(edgeTiles[tileAutoID], tilePos, edgeTiles[tileAutoID].transform.rotation); tileObj.transform.parent = transform; CoastTile cT = new CoastTile(tile.loc, worldLoc3, 'G', tileObj); newTiles[(mapWidth * y) + x] = cT; } } else if (tileType == 'W') { GameObject tileObj = (GameObject)Instantiate(clearTile, tilePos, clearTile.transform.rotation); tileObj.transform.parent = transform; tileObj.SetActive(false); OceanTile oT = new OceanTile(tile.loc, worldLoc3, 'W', tileObj); newTiles[(mapWidth * y) + x] = oT; } } } tiles = newTiles; }
public int CompareTo(ResourceTileDescriptor other) { ResourceTile resourceTile = (ResourceTile)Tile; ResourceTile otherResourceTile = (ResourceTile)other.Tile; double resourceScore = 1 / resourceTile.AmountLeft + 1 / resourceTile.Density + Path.Count; double otherResourceScore = 1 / otherResourceTile.AmountLeft + 1 / otherResourceTile.Density + other.Path.Count; return(resourceScore.CompareTo(otherResourceScore)); }
public void Initialize(Tile t_originTile, City t_city) { m_cityOwner = t_city; transform.position = t_originTile.transform.position; transform.SetParent(t_originTile.transform); m_resourceTile = t_originTile.GetResourceTile(); GetComponent <SpriteRenderer>().sprite = m_buildingSprites[(int)m_resourceTile.GetResourceType()]; }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return !( tile.hasOutpost || tile.baseCoverType != BaseCoverType.Developed || tile.zoneType != ZoneType.Residential || tile.housingCapacity > 0 || tile.housingOccupants > 0 ); }
public void Reset() { CloseCharacterInfoPanel(); CloseInventory(); selectedObject = null; villagerReference = null; resourceReference = null; buildingReference = null; }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return !( tile.baseCoverType == BaseCoverType.Barren || tile.baseCoverType == BaseCoverType.CultivatedCrops || tile.baseCoverType == BaseCoverType.Excluded || tile.baseCoverType == BaseCoverType.Unknown || tile.baseCoverType == BaseCoverType.Water || tile.supportedSaplings == 0 ); }
public ResourceTile CreateTile(ResourceTile _baseTile) { ResourceTile _newTile = ScriptableObject.CreateInstance <ResourceTile>(); _newTile.sprite = _baseTile.sprite; _newTile.SetHealth(_baseTile.Health); _newTile.Resource = _baseTile.Resource; _newTile.glowObject = _baseTile.glowObject; return(_newTile); }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return !( tile.zoneType != ZoneType.Residential || tile.baseCoverType == BaseCoverType.Excluded || tile.baseCoverType == BaseCoverType.Unknown || tile.baseCoverType == BaseCoverType.Water || tile.housingOccupants > 0 || (tile.baseCoverType == BaseCoverType.Developed && tile.housingCapacity == 0 && !tile.hasOutpost) ); }
/// <summary> /// Create a region that includes all of the specified tiles /// </summary> /// <param name="tiles"> /// A <see cref="ResourceTile"/> /// </param> public Region(ResourceTile[] tiles) { left = tiles[0].x; right = tiles[0].x; top = tiles[0].z; bottom = tiles[0].z; foreach (ResourceTile tile in tiles) { bottom = Mathf.Min(bottom, tile.z); top = Mathf.Max(top, tile.z); left = Mathf.Min(left, tile.x); right = Mathf.Max(right, tile.x); } }
public void SelectWorkArea(GameObject objectReference) { //Debug.Log("Work Area Selected"); targetObject = objectReference; if (objectReference.GetComponent <ResourceTile>()) { workingResource = objectReference.GetComponent <ResourceTile>(); } currentState = CHARACTER_STATE.CHARACTER_MOVING; }
public override void execute(BaseAgentBehavior owner) { if (map == null) { map = ((VesselBehavior)owner).resourceMap; } ResourceGrid grid = map.GetComponent <MarineResourceBehavior>().grid; ResourceTile mostTile = grid.resourceTiles.ElementAt(UnityEngine.Random.Range(0, grid.resourceTiles.Count)).Value; destination.getComponent <Destination>().destination = mostTile; Debug.Log("Fishing location set "); }
IEnumerator GetFish() { if (tile is null) { tile = cachedInFilter.getEntity <Destination>().getComponent <Destination>().destination; } tile.isHere(owner.gameObject); //fish(mostTile.tileIndex()); tile.fishingHere(owner.gameObject); yield return(null); currentCatch = tile.getFish(owner.gameObject); yield return(null); tile.leftHere(owner.gameObject); }
List <Vector3Int> getNeighbors(Vector3Int tileIndex) { ResourceTile tile = grid.getTileAt(tileIndex); List <Vector3Int> list = new List <Vector3Int>(); if (tile.neighbors.S != null) { list.Add(tile.neighbors.S.tileIndex()); } if (tile.neighbors.SE != null) { list.Add(tile.neighbors.SE.tileIndex()); } if (tile.neighbors.SW != null) { list.Add(tile.neighbors.SW.tileIndex()); } if (tile.neighbors.N != null) { list.Add(tile.neighbors.N.tileIndex()); } if (tile.neighbors.NE != null) { list.Add(tile.neighbors.NE.tileIndex()); } if (tile.neighbors.NW != null) { list.Add(tile.neighbors.NW.tileIndex()); } if (tile.neighbors.E != null) { list.Add(tile.neighbors.E.tileIndex()); } if (tile.neighbors.W != null) { list.Add(tile.neighbors.W.tileIndex()); } return(list); }
public IEnumerator CheckResourceTileSetup() { m_tile.SetTileType(TileType.Land); GameObject resourcePrefab = Resources.Load <GameObject>("Prefabs/ResourceTile"); GameObject resourceObject = GameObject.Instantiate(resourcePrefab); ResourceTile resource = resourceObject.GetComponent <ResourceTile>(); resource.Setup(m_tile, ResourceType.Wheat); Assert.True(m_tile.transform.position == resource.transform.position); Assert.True(resource.transform.parent == m_tile.transform); Assert.True(resource.GetResourceType() == ResourceType.Wheat); Assert.True(m_tile.GetProduction() == 0); Assert.True(m_tile.GetFood() == 3); yield return(null); }
public static List<int> GetTileIdsInRadius(ResourceTile tile, float radius) { List<int> tiles = new List<int>(); Vector3 pos; for (int rr=-(int)radius; rr<(int)radius; rr++) { for (int cc=-(int)radius; cc<(int)radius; cc++) { pos = new Vector3(tile.x,tile.y,tile.z); if (!IsWorldPositionInRadius(pos,pos + new Vector3(cc,0,rr), 20f)) { continue; } try { Debug.Log("Added a Tile"); tiles.Add(TerrainManager.use.resourceTileCache[tile.y+rr,tile.x+cc].id); } catch (System.IndexOutOfRangeException) { continue; } } } return tiles; }
List <ResourceTile> getNeighbors(ResourceTile tile) { //ResourceTile tile = grid.getTileAt(tileIndex.x, tileIndex.y); List <ResourceTile> list = new List <ResourceTile>(); if (tile.neighbors.N != null) { list.Add(tile.neighbors.N); } if (tile.neighbors.NE != null) { list.Add(tile.neighbors.NE); } if (tile.neighbors.NW != null) { list.Add(tile.neighbors.NW); } if (tile.neighbors.E != null) { list.Add(tile.neighbors.E); } if (tile.neighbors.W != null) { list.Add(tile.neighbors.W); } if (tile.neighbors.S != null) { list.Add(tile.neighbors.S); } if (tile.neighbors.SE != null) { list.Add(tile.neighbors.SE); } if (tile.neighbors.SW != null) { list.Add(tile.neighbors.SW); } return(list); }
public void addTiles(mEntity profile) { Tilemap map = profile.getComponent <ResourceTileMap>().map; sizeX = profile.getComponent <MapSize>().x; sizeY = profile.getComponent <MapSize>().y; maxCarry = profile.getComponent <MaxCarry>().maxcarry; float growthrate = profile.getComponent <GrowthRate>().rate; for (int i = 0; i < sizeX; i++) { for (int j = 0; j < sizeY; j++) { if (map.GetTile(new Vector3Int(i, j, 0)) != null) { ResourceTile tile = new ResourceTile(); float randX = Random.Range(0f, 200f); float randY = randX;//Random.Range(0f, 200f); tile.carryCapacity = Mathf.PerlinNoise((i + randX) / (randX + sizeX), (j + randX) / (randX + sizeY)) * maxCarry * 2; tile.currentResource = tile.carryCapacity * startingResourcePercentage; tile.updatedResource = tile.currentResource; tile.growthRate = growthrate; tile.x = i; tile.y = j; resourceTiles.Add(new Vector3Int(i, j, 0), tile); index++; } } } addNeighbors(); Debug.Log("Cells added to resource grid: " + index); }
void Start() { for (int i = tilemap.cellBounds.xMin; i < tilemap.cellBounds.xMax; i++) { for (int j = tilemap.cellBounds.yMin; j < tilemap.cellBounds.yMax; j++) { Tile tile = tilemap.GetTile <Tile>(new Vector3Int(i, j, 0)); if (tile == null) { continue; } TileType tileType = CheckType(tile); if (Config.Instance.TileConfig.ResourceTiles.Contains(tileType)) { storageMap[FlatIndex(i, j)] = new ResourceTile(Config.Instance.TileConfig.TileStartingValues[CheckType(tile)]); } } } }
IEnumerator toRandomDest() { if (grid != null) { ResourceTile mostTile = grid.resourceTiles.ElementAt(Random.Range(0, grid.resourceTiles.Count)).Value; moveBoat(mostTile.tileIndex()); mostTile.isHere(gameObject); //fish(mostTile.tileIndex()); mostTile.fishingHere(gameObject); yield return(null); mostTile.getFish(gameObject); currentGrossProfit = currentCatch * fishPrice; currentProfit = currentCatch * fishPrice - costs; yield return(new WaitForSeconds(1f)); mostTile.leftHere(gameObject); keepFishing(mostTile.tileIndex()); } }
ResourceTile bestNeighbor(ResourceTile tile) { List <Vector3Int> neighbors = getNeighbors(tile.tileIndex()); float mostResource = tile.currentResource / (tile.boatsHere.Count + 1); ResourceTile mostTile = tile; for (int i = 0; i < neighbors.Count; i++) { ResourceTile rtile = grid.getTileAt(neighbors[i]); float bla = rtile.currentResource / (rtile.boatsHere.Count + 1); // Debug.Log(bla); if (bla > mostResource) { mostResource = bla; mostTile = rtile; } } return(mostTile); }
public void addTiles(Tilemap map, int x, int y, SimProfile sim) { sizeX = x; sizeY = y; maxCarry = sim.getMaxCarry(); for (int i = 0; i < sizeX; i++) { for (int j = 0; j < sizeY; j++) { if (map.GetTile(new Vector3Int(i, j, 0)) != null) { ResourceTile tile = new ResourceTile(); float randX = Random.Range(0f, 200f); float randY = randX;//Random.Range(0f, 200f); tile.carryCapacity = Mathf.PerlinNoise((i + randX) / (randX + sizeX), (j + randX) / (randX + sizeY)) * maxCarry * 2; tile.currentResource = tile.carryCapacity * startingResourcePercentage; tile.updatedResource = tile.currentResource; tile.growthRate = sim.growthRate; tile.x = i; tile.y = j; resourceTiles.Add(new Vector3Int(i, j, 0), tile); index++; } } } addNeighbors(); Debug.Log("Cells added to resource grid: " + index); }
public bool HandleMouseInput(MouseInput mi) { // Exclusively uses left and right mouse buttons, but nothing else // Mouse move events are important for tooltips, so we always allow these through if (mi.Button != MouseButton.Left && mi.Button != MouseButton.Right && mi.Event != MouseInputEvent.Move) { return(false); } var cell = worldRenderer.Viewport.ViewToWorld(mi.Location); if (mi.Event == MouseInputEvent.Up) { return(true); } var underCursor = editorLayer.PreviewsAt(worldRenderer.Viewport.ViewToWorldPx(mi.Location)) .FirstOrDefault(); var mapResources = world.Map.MapResources.Value; ResourceType type; if (underCursor != null) { editorWidget.SetTooltip(underCursor.Tooltip); } else if (mapResources.Contains(cell) && resources.TryGetValue(mapResources[cell].Type, out type)) { editorWidget.SetTooltip(type.Info.Name); } else { editorWidget.SetTooltip(null); } // Finished with mouse move events, so let them bubble up the widget tree if (mi.Event == MouseInputEvent.Move) { return(false); } if (mi.Button == MouseButton.Right) { editorWidget.SetTooltip(null); if (underCursor != null) { editorLayer.Remove(underCursor); } if (mapResources.Contains(cell) && mapResources[cell].Type != 0) { mapResources[cell] = new ResourceTile(); } } else if (mi.Button == MouseButton.Left && mi.Event == MouseInputEvent.Down) { if (underCursor != null) { // Test case / demonstration of how to edit an existing actor var facing = underCursor.Init <FacingInit>(); if (facing != null) { underCursor.ReplaceInit(new FacingInit((facing.Value(world) + 32) % 256)); } else if (underCursor.Info.Traits.WithInterface <UsesInit <FacingInit> >().Any()) { underCursor.ReplaceInit(new FacingInit(32)); } var turret = underCursor.Init <TurretFacingInit>(); if (turret != null) { underCursor.ReplaceInit(new TurretFacingInit((turret.Value(world) + 32) % 256)); } else if (underCursor.Info.Traits.WithInterface <UsesInit <TurretFacingInit> >().Any()) { underCursor.ReplaceInit(new TurretFacingInit(32)); } } } return(true); }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { //return TerrainManager.use.IsWorldPositionInRadiusOfAnyOutpost(tile.GetSimpleCenterPoint()) && !tile.is_surveyed; return (!tile.is_surveyed && tile.can_be_surveyed); }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return true; }
IEnumerator DrillRepeated() { if (drillActive || !vehicleMover.IsMining) { vehicleMain.Audio.StopAudio(VehicleSounds.Drilling); yield break; } int _hardnessCount = 0; while (true) { float gasLeft = vehicleMain.Inventory.GetFuelAmount(); if (!drillActive && vehicleMover.IsMining) { drillActive = true; } else if (!vehicleMover.IsMining || gasLeft <= 0) { vehicleMain.Audio.StopAudio(VehicleSounds.Drilling); drillActive = false; yield break; } _hardnessCount = 0; RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, drillCollider.radius, transform.forward, drillCollider.radius, miningLayerMask); if (hits.Length > 0) { print(hits[0].transform.gameObject.layer); bool hasChanged = false; foreach (RaycastHit2D hit in hits) { //print("DrillRepeated"); Vector2 hitPosition = new Vector2(); hitPosition.x = hit.point.x; hitPosition.y = hit.point.y; hitPosition.x = hit.point.x; hitPosition.y = hit.point.y; if (tilemap.GetTile(tilemap.WorldToCell(hitPosition)) != null) { ResourceTile _tile = tilemap.GetTile <ResourceTile>(tilemap.WorldToCell(hitPosition)); if (_tile.Hardness <= vehicleMain.DrillTier) { int damage = 5; float collectionBonus = 1; vehicleMain.Audio.PlayAudio(VehicleSounds.Drilling); WorkerBase _drillOperater = vehicleMain.GetWorker(WorkStation.Drill); if (_drillOperater != null) { damage += _drillOperater.Operating; collectionBonus = (float)_drillOperater.Operating * 0.25f; } if (vehicleMain.GetWorker(WorkStation.Spare) != null) { damage += Mathf.RoundToInt((float)vehicleMain.GetWorker(WorkStation.Spare).Operating / 2f); } _tile.TakeDamage(damage); //print("Tile Health " + _tile.Health); if (_tile.Health <= 0) { //Add a resource vehicleMain.Inventory.AddResource(_tile.Resource, (1 * vehicleMain.DrillEfficiency) + collectionBonus); tilemap.SetTile(tilemap.WorldToCell(hitPosition), null); hasChanged = true; } } else { _hardnessCount++; } vehicleMain.UseFuel(-1 * vehicleMain.DrillFuelEfficiency); } //Code for Particle system spawning. //CreateParticle(this.transform.position); drill.transform.parent = drill.transform; //Consume a fuel with every block mined if (_hardnessCount >= hits.Length) { Debug.LogWarning("Soil is too hard"); vehicleMain.Audio.StopAudio(VehicleSounds.Drilling); drillActive = false; yield break; } } if (hasChanged) { GameObject.FindObjectOfType <PlayerController>().dirtyNav = true; } } else { vehicleMain.Audio.StopAudio(VehicleSounds.Drilling); drillActive = false; yield break; } yield return(new WaitForSeconds(vehicleMain.DrillSpeed)); } }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return !( tile.isHarvestArea || tile.zoneType == ZoneType.Protected || tile.baseCoverType == BaseCoverType.Excluded || tile.baseCoverType == BaseCoverType.Unknown || tile.baseCoverType == BaseCoverType.Water || // TODO: server throws a 500 if land cover class code is not one of the following ( tile.landCoverType != LandCoverType.Coniferous && tile.landCoverType != LandCoverType.Deciduous && tile.landCoverType != LandCoverType.Mixed && tile.landCoverType != LandCoverType.ForestedWetland ) ); }
/// <summary> /// Sets the permissions. /// </summary> /// <param name='tiles'> /// Tiles from which to read permissions. /// </param> public void SetPermissions(ResourceTile[] tiles) { int xOffset = (int)terrain.transform.position.x; int zOffset = (int)terrain.transform.position.z; foreach (ResourceTile tile in tiles) { // get coordinates in the space of the chunk int x = tile.x - xOffset; int z = tile.z - zOffset; resourceTileCache[z,x].permittedActions = tile.permittedActions; } // update mask if displayed InputManager.use.currentAction.UpdateMask(); // update selection //InputManager.use.FilterSelection(); InputManager.use.currentAction.UpdateSelectionHighlighter(); }
void load (string filename) { // Read the file System.IO.StreamReader file = new System.IO.StreamReader (filename); //load mapsize from file //type octile file.ReadLine (); //height this.sizeY = Int32.Parse (file.ReadLine ().Split (' ') [1]); //width this.sizeX = Int32.Parse (file.ReadLine ().Split (' ') [1]); //"map" file.ReadLine (); //init maptiles array this.mapTiles = new char[sizeX, sizeY]; //initialize entity array this.entities = new MapObject[sizeX, sizeY]; //fill maptiles from file string line; int lineCount = 0; while ((line = file.ReadLine()) != null) { for (int i = 0; i < line.Length; i++) { mapTiles [i, lineCount] = line [i]; if (Trees.Contains (mapTiles [i, lineCount])) { entities [i, lineCount] = new ResourceTile (); ((ResourceTile)entities [i, lineCount]).setTile (ResourceType.Timber, new IVec2 (i, lineCount)); } else if (Terrain.Contains (mapTiles [i, lineCount])) { if (UnityEngine.Random.Range (0.0f, 1.0f) < ResourceChance) { ResourceType t = ((UnityEngine.Random.Range (1, 100) % 2) == 0) ? ResourceType.Ore : ResourceType.Coal; ResourceTile rt = new ResourceTile (); entities [i, lineCount] = rt; rt.setTile (t, new IVec2 (i, lineCount)); } } else { entities [i, lineCount] = new MapObject (); } } lineCount++; } //close file file.Close (); }
public bool HandleMouseInput(MouseInput mi) { // Exclusively uses mouse wheel and right mouse buttons, but nothing else // Mouse move events are important for tooltips, so we always allow these through if ((mi.Button != MouseButton.Right && mi.Event != MouseInputEvent.Move && mi.Event != MouseInputEvent.Scroll) || mi.Event == MouseInputEvent.Down) return false; worldPixel = worldRenderer.Viewport.ViewToWorldPx(mi.Location); var cell = worldRenderer.Viewport.ViewToWorld(mi.Location); var underCursor = editorLayer.PreviewsAt(worldPixel).MinByOrDefault(CalculateActorSelectionPriority); var mapResources = world.Map.Resources; ResourceType type; if (underCursor != null) editorWidget.SetTooltip(underCursor.Tooltip); else if (mapResources.Contains(cell) && resources.TryGetValue(mapResources[cell].Type, out type)) editorWidget.SetTooltip(type.Info.Type); else editorWidget.SetTooltip(null); // Finished with mouse move events, so let them bubble up the widget tree if (mi.Event == MouseInputEvent.Move) return false; if (mi.Button == MouseButton.Right) { editorWidget.SetTooltip(null); if (underCursor != null) editorLayer.Remove(underCursor); if (mapResources.Contains(cell) && mapResources[cell].Type != 0) mapResources[cell] = new ResourceTile(); } else if (mi.Event == MouseInputEvent.Scroll) { if (underCursor != null) { // Test case / demonstration of how to edit an existing actor var facing = underCursor.Init<FacingInit>(); if (facing != null) underCursor.ReplaceInit(new FacingInit((facing.Value(world) + mi.ScrollDelta) % 256)); else if (underCursor.Info.HasTraitInfo<UsesInit<FacingInit>>()) underCursor.ReplaceInit(new FacingInit(mi.ScrollDelta)); var turret = underCursor.Init<TurretFacingInit>(); if (turret != null) underCursor.ReplaceInit(new TurretFacingInit((turret.Value(world) + mi.ScrollDelta) % 256)); else if (underCursor.Info.HasTraitInfo<UsesInit<TurretFacingInit>>()) underCursor.ReplaceInit(new TurretFacingInit(mi.ScrollDelta)); } } return true; }
/// <summary> /// Computes the center point based on the bounds of the tile positions. /// </summary> /// <returns> /// The center point. /// </returns> public IEnumerator ComputeCenterPoint() { HTTP.Request request = new HTTP.Request( "Get", WebRequests.GetURLToResourceTile(this.ids[0]) ); request.AddParameters( WebRequests.authenticatedGodModeParameters ); request.Send(); while( !request.isDone ) { yield return 0; } if( request.ProducedError ) { Debug.LogError( "Unable to compute center point of harvest: " + request.Error ); yield break; }; ResourceTile tile = new ResourceTile(); try { tile = JSONDecoder.Decode<IndividualResourceTile>(request.response.Text).resource_tile; } catch (JsonException) { Debug.LogError("Error parsing json data:\n"+request.response.Text); } Bounds bounds = new Bounds(tile.GetSimpleCenterPoint(), new Vector3(1f,0f,1f)); foreach (int id in this.ids) { request = new HTTP.Request( "Get", WebRequests.GetURLToResourceTile(id) ); request.AddParameters( WebRequests.authenticatedGodModeParameters ); request.Send(); while( !request.isDone ) { yield return 0; } if( request.ProducedError ) { Debug.LogError( "Unable to compute center point of harvest: " + request.Error ); yield break; } try { tile = JSONDecoder.Decode<IndividualResourceTile>(request.response.Text).resource_tile; bounds.Encapsulate(tile.GetSimpleCenterPoint()); } catch (JsonException) { Debug.LogError("Error parsing json data:\n"+request.response.Text); } } // set the center point from the bounding box this.centerPoint = bounds.center; }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public abstract bool IsPermittedOnResourceTile(ResourceTile tile);
public PowerPlant(GameplayManager gm, int gridX, int gridY, int faction, World world, Grid grid) : base(gm, gridX, gridY, faction, world, 1, 1, 300,100.0f, 100, grid) { powerSource = (ResourceTile)grid.GetTile(gridX, gridY); }
void SetTile(CPos cell, ResourceTile tile) { map.Resources[cell] = tile; }
public CellResource(CPos cell, ResourceTile resourceTile, ResourceTile newResourceTile) { Cell = cell; ResourceTile = resourceTile; NewResourceTile = newResourceTile; }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return base.IsPermittedOnResourceTile(tile); }
//used only for testing public void setResourcetile (ResourceType type, int ResourceAmount, IVec2 MapPos) { ResourceTile t = new ResourceTile (); t.setTile (type, MapPos, ResourceAmount); }
/// <summary> /// Sets the terrain from resourceTiles. /// </summary> /// <param name='resourceTiles'> /// Microtiles. /// </param> /// <param name='mode'> /// Mode. /// </param> public void SetTerrainFromResourceTiles(ResourceTile[] resourceTiles, SetTerrainMode mode) { if (resourceTiles.Length <= 0) { // return; // if this case actually gets hit I want to know what is causing it. throw new System.ArgumentException("Please find out why the resourceTile array was empty and tell Adam."); } // if the view is not entirely terrain, clear it and move it to the center of the view if (!m_isTerrainFixedInPlace && !CameraRig.use.isViewFrustumEntirelyTerrain ) { ClearTerrain(SetTerrainMode.NoFlush); MoveTerrainToCenterOfView(); } // determine region of update to minimize calls to Terrain APIs Region region = new Region(resourceTiles); // clear structures in the region ClearBuildingsInRegion(region); // convert to terrain-space region region.ToTerrainRegion( out region ); // get current properties for the region float[,] heights = terrainData.GetHeights(region.left, region.bottom, region.width, region.height); float[,,] splats = terrainData.GetAlphamaps(region.left, region.bottom, region.width, region.height); int[][,] details = new int[terrainData.detailPrototypes.Length][,]; for (int i=0; i<details.Length; i++) { details[i] = terrainData.GetDetailLayer(region.left, region.bottom, region.width, region.height, i); } // update values as needed int xOffset = (int)terrain.transform.position.x + region.left; int zOffset = (int)terrain.transform.position.z + region.bottom; Building b = null; foreach (ResourceTile tile in resourceTiles) { // get coordinates in the space of the chunk int x = tile.x - xOffset; int z = tile.z - zOffset; // skip any resourceTiles that are out of bounds, as when e.g., server returns a bigger cached chunk than we need if (x<0 || x>heights.GetUpperBound(1) || z<0 || z>heights.GetUpperBound(0) ) { continue; } // // cache stuff that is not collapsed into other representations // resourceTileCache[region.bottom+z,region.left+x] = new ResourceTileLite(tile); // set heights GroundTextureType ground = tile.groundTextureType; heights[z,x] = (ground==GroundTextureType.Water)?0f:terrainData.size.y; // set ground texture for (int i=0; i<=splats.GetUpperBound(2); ++i) { splats[z,x,i] = 0f; } splats[z,x,(int)ground] = 1f; // get the raw number of trees of each type int[] treeCounts = tile.GetTreeCountsByGraphicType(); // remap tree counts to the range for detail values for (int i=0; i<treeCounts.Length; ++i) { treeCounts[i] = (int)(detailResolutionPerPatch*Mathf.Min(treeCounts[i]*ResourceTile.oneOverMaxNumberOfTreesPerAcre, 1f)); } // set details for (int i=0; i<treeCounts.Length; ++i) { details[i][z,x] = treeCounts[i]; } // add structures if (tile.hasOutpost && !m_outpostInstances.ContainsKey(tile.id)) { m_outpostInstances.Add( tile.id, Instantiate(m_outpostPrefab, tile.GetCenterPoint(), Quaternion.identity) as ResearchOutpost ); } else if (!tile.hasOutpost && m_outpostInstances.ContainsKey(tile.id)) { Destroy(m_outpostInstances[tile.id].gameObject); m_outpostInstances.Remove(tile.id); } b = buildHousingAction.GetBuildingWithCapacity(tile.housingCapacity); if (b==null) { continue; } Building building = Instantiate(b, tile.GetCenterPoint(), Quaternion.identity) as Building; building.gameObject.transform.parent = m_objectGrouper.transform; m_buildingInstances.Add(building.gameObject); } // cache stuff that is not collapsed into other representations // NOTE: must do afterward for now, since it relies on e.g. research outpost locations; can go back once server sets permissions foreach (ResourceTile tile in resourceTiles) { // get coordinates in the space of the chunk int x = tile.x - xOffset; int z = tile.z - zOffset; // skip any resourceTiles that are out of bounds, as when e.g., server returns a bigger cached chunk than we need if (x<0 || x>heights.GetUpperBound(1) || z<0 || z>heights.GetUpperBound(0) ) { continue; } resourceTileCache[region.bottom+z,region.left+x] = new ResourceTileLite(tile); } // apply results terrainData.SetHeights(region.left, region.bottom, heights); terrainData.SetAlphamaps(region.left, region.bottom, splats); for (int i=0; i<details.Length; i++) { terrainData.SetDetailLayer(region.left, region.bottom, i, details[i]); } // set the cleared flag if (region.width>0 && region.height>0) { m_isTerrainDataCleared = false; } // flush if requested if (mode == SetTerrainMode.Flush) { terrain.Flush(); } // broadcast that tiles have finished loading MessengerAM.Send(new MessageLoadedNewTiles(region)); Messenger<Region>.Broadcast(kLoadedNewTiles,region); }
/// <summary> /// Initializes a new instance of the <see cref="ResourceTileLite"/> struct. /// </summary> /// <param name='rawTileData'> /// Raw tile data. /// </param> public ResourceTileLite (ResourceTile rawTileData) : this() { this.id = rawTileData.id; this.idOwner = rawTileData.idOwner; this.idMegatile = rawTileData.idMegatile; this.x = rawTileData.x; this.y = rawTileData.z; this.zone = rawTileData.zoneType; this.permittedActions = rawTileData.permittedActions; this.baseCoverType = rawTileData.baseCoverType; this.treeCount = rawTileData.totalTreeCount; this.boughtByDeveloper = rawTileData.bought_by_developer; this.boughtByTimberCompany = rawTileData.bought_by_timber_company; this.desirability = (float)rawTileData.total_desirability_score; this.surveyRequested = rawTileData.survey_requested; this.canBeSurveyed = rawTileData.can_be_surveyed; this.isSurveyed = rawTileData.is_surveyed; this.outpostRequested = rawTileData.outpost_requested; this.animalCount = 0; }
public bool HandleMouseInput(MouseInput mi) { // Exclusively uses mouse wheel and both mouse buttons, but nothing else // Mouse move events are important for tooltips, so we always allow these through if ((mi.Button != MouseButton.Left && mi.Button != MouseButton.Right && mi.Event != MouseInputEvent.Move && mi.Event != MouseInputEvent.Scroll) || mi.Event == MouseInputEvent.Down) { return(false); } worldPixel = worldRenderer.Viewport.ViewToWorldPx(mi.Location); var cell = worldRenderer.Viewport.ViewToWorld(mi.Location); var underCursor = editorLayer.PreviewsAt(worldPixel).MinByOrDefault(CalculateActorSelectionPriority); var mapResources = world.Map.Resources; ResourceType type; if (underCursor != null) { editorWidget.SetTooltip(underCursor.Tooltip); } else if (mapResources.Contains(cell) && resources.TryGetValue(mapResources[cell].Type, out type)) { editorWidget.SetTooltip(type.Info.Type); } else { editorWidget.SetTooltip(null); } // Finished with mouse move events, so let them bubble up the widget tree if (mi.Event == MouseInputEvent.Move) { return(false); } if (mi.Button == MouseButton.Left) { editorWidget.SetTooltip(null); SelectedActor = underCursor; } if (mi.Button == MouseButton.Right) { editorWidget.SetTooltip(null); if (underCursor != null && underCursor != SelectedActor) { editorLayer.Remove(underCursor); } if (mapResources.Contains(cell) && mapResources[cell].Type != 0) { mapResources[cell] = new ResourceTile(); } } return(true); }
private void onMouseClickEvent(Vector3 point) { Vector3Int cellIndex = resourceMap.WorldToCell(point); Destroy(existingHighlight); existingHighlight = null; foreach (GameObject g in neighborHighlights) { Destroy(g); } neighborHighlights.Clear(); if (grid.getTileAt(cellIndex.x, cellIndex.y) != null) { GameObject tile = Instantiate(highlight, resourceMap.GetCellCenterLocal(cellIndex), Quaternion.identity); if (existingHighlight == null) { existingHighlight = tile; } //add neighbor highlights ResourceTile target = grid.getTileAt(cellIndex.x, cellIndex.y); if (target.neighbors.N != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x, cellIndex.y + 1, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.NE != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x + 1, cellIndex.y + 1, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.E != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x + 1, cellIndex.y, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.SE != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x + 1, cellIndex.y - 1, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.S != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x, cellIndex.y - 1, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.SW != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x - 1, cellIndex.y - 1, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.W != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x - 1, cellIndex.y, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } if (target.neighbors.NW != null) { GameObject ntile = Instantiate(neighborHighlight, resourceMap.GetCellCenterLocal(new Vector3Int(cellIndex.x - 1, cellIndex.y + 1, 0)), Quaternion.identity); neighborHighlights.Add(ntile); } float resource = target.currentResource; resourceTileText.GetComponent <Text>().text = "Resource in tile: " + target.currentResource;// resource; neighborsText.GetComponent <Text>().text = "Tile neighbors: " + neighborHighlights.Count; boatsAtTileText.GetComponent <Text>().text = "Boats: " + target.boatsHere.Count; } //Debug.Log("Position: " + point + " [" + cellIndex + "]"); //setTileColor(Random.ColorHSV(), cellIndex, resourceMap); }
/// <summary> /// Determines whether this instance is permitted on resource tile the specified tile. /// </summary> /// <returns> /// <c>true</c> if this instance is permitted on resource tile the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// If set to <c>true</c> tile. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return ( tile.zoneType == ZoneType.None ); }
/// <summary> /// Determines whether this action is permitted on the specified tile. /// </summary> /// <returns> /// <c>true</c> if this action is permitted on the specified tile; otherwise, <c>false</c>. /// </returns> /// <param name='tile'> /// The resource tile in question. /// </param> public override bool IsPermittedOnResourceTile(ResourceTile tile) { return tile.is_surveyed; }
/// <summary> /// Sends out a message stating that an action was performed /// </summary> protected virtual void SendActionMessage(ResourceTile[] modifiedTiles) { Messenger<int>.Broadcast(string.Format("{0}_Count",notificationMessage,modifiedTiles.Length), modifiedTiles.Length); }
public void Do() { resourceTile = mapResources[cell]; mapResources[cell] = default(ResourceTile); }
protected override void SendActionMessage(ResourceTile[] modifiedTiles) { Messenger<CutType>.Broadcast(notificationMessage, m_cutType); base.SendActionMessage(modifiedTiles); }