public void AddBaseTile(BaseTile.eDirection start, BaseTile.eDirection end) { int idx = -1; for (int i = 0; i < tiles.Length; i++) { if (tiles[i] == null || tiles[i].transform.parent != tileRoot) { idx = i; } } if (idx == -1) { idx = Random.Range(0, 4); } if (tiles[idx] != null && tiles[idx].transform.parent == tileRoot) { Destroy(tiles[idx].gameObject); } BaseTile newTile = Instantiate(baseTilePrefab); newTile.name = "BaseTile" + ((int)Random.Range(0.0f, 128.0f)); newTile.SetDirections(start, end); newTile.transform.parent = tileRoot; newTile.transform.position = new Vector3(13.0f, 0, 10.0f + 3.0f * idx); tiles[idx] = newTile; }
void CreateTile(Cell cell) { GameObject tile = Instantiate(tileTemplate); BaseTile baseTile = tile.GetComponent <BaseTile>(); baseTile.InitTile(cell, Random.Range(1, Constants.amountOfColors + 1), this); }
public void Draw(SpriteBatch spriteBatch, Vector2 offset = default(Vector2)) { foreach (List <BaseTile> column in Tiles) { foreach (BaseTile tile in column) { tile.Draw(spriteBatch, offset); } } if (this.HighlightedTile != null) { spriteBatch.Draw(Textures.TileHover, new Vector2(HighlightedTile.CanvasX, HighlightedTile.CanvasY) + offset, Color.White); } if (this.SelectedTemplate != null && this.HighlightedTile != null) { List <Vector2> affectedTilesCoords = this.SelectedTemplate.GetAffectedTiles(new Vector2(this.HighlightedTile.PosX, this.HighlightedTile.PosY)); foreach (Vector2 tileCoords in affectedTilesCoords) { BaseTile tile = GetTileAtCoords((int)tileCoords.X, (int)tileCoords.Y); if (tile != null) { Vector2 canvasPos = new Vector2(tile.CanvasX, tile.CanvasY); spriteBatch.Draw(Textures.RedFilter, canvasPos + offset, Color.White); } } } }
private void ChainTiles(string line) { // Remove tab and space elements line = Regex.Replace(line, @"[\t|\s]", string.Empty); // Split on each column (seperated by ':') var column = line.Split(':'); // Get position out of first column var aPosFrom = column[0].Trim().Split(','); Point posFrom = new Point { X = Int32.Parse(aPosFrom[0]), Y = Int32.Parse(aPosFrom[1]) }; // Get position out of second column var aPosTo = column[1].Trim().Split(','); Point posTo = new Point { X = Int32.Parse(aPosTo[0]), Y = Int32.Parse(aPosTo[1]) }; // Chain them BaseTile tileFrom = _tiles.FirstOrDefault(item => item.Pos == posFrom); BaseTile tileTo = _tiles.FirstOrDefault(item => item.Pos == posTo); tileFrom.ChainTiles(tileTo); }
protected override void OnArrived(BaseUnit unit, BaseTile previousTile) { base.OnArrived(unit, previousTile); if ((_opened || debugOpen) && unit is AvatarUnit) { for (int i = 0; i < LevelSelectionAndUILogic.ListOfAllLevelJSON.Count; i++) { if (LevelSelectionAndUILogic.ListOfAllLevelJSON[i].Name.Equals(Application.loadedLevelName)) { LevelSelectionAndUILogic.ListOfAllLevelJSON[i].IsPassed = true; //LevelSelectionAndUILogic.ListOfAllLevelJSON[i].IsActive = true; //its sufficient with just setting the current map to "haspassed" true, as its just first the first level that uses is active, but if future changes need em its here... //LevelSelectionAndUILogic.ListOfAllLevelJSON[i + 1].IsActive = true; //same comment as above. break; } } LevelSelectionAndUILogic.SaveToJson(); //saves the level progression StartCoroutine(_sceneTransition.LoadLevelWithDelay(0.1f, "NEW_GameStartScene")); } if (IsPortalTile && !_opened) { TeleportUnit(unit, previousTile, DestinationTeleportTile); } }
public BuildingItem(BaseTile tile, int count) { Type = BuildingItemType.TILE; Prefab = tile.Prefab; Name = tile.Name; Count = count; }
protected override void OnArrived(BaseUnit unit, BaseTile previousTile) { base.OnArrived(unit, previousTile); if (redObjectsToNotify != null) { foreach (EventListener el in redObjectsToNotify) { el.ReceiveEvent(EventMessage.ToggleUpDown); } foreach (EventListener el in blueObjectsToNotify) { el.ReceiveEvent(EventMessage.ToggleUpDown); } foreach (EventListener el in RedBlueButtonTilesToNotify) { el.ReceiveEvent(EventMessage.ToggleColor); } } else { Debug.Log("redObjectsToNotify has not been set"); } if (IsPortalTile) { TeleportUnit(unit, previousTile, DestinationTeleportTile); } }
public void NewLevelStarted(GameObject LevelHead) { NoOfTilesInLevel = LevelHead.transform.childCount - 1; LevelStartTile = LevelHead.GetComponent <LevelManager>().GetLevelStart(); LevelEndTile = LevelHead.GetComponent <LevelManager>().GetLevelEnd(); ResetLocalLevelAtributes(); }
public void RemoveAxles() { if (AllAxles) { Destroy(AllAxles); } AllAxles = Instantiate(new GameObject()); AllAxles.name = "AllAxles"; AllAxles.transform.parent = CurrentLevel.transform; foreach (Transform CurrTile in CurrentLevel.transform) { if (CurrTile.GetComponent <BaseTile>()) { BaseTile LocalCopy = CurrTile.GetComponent <BaseTile>(); LocalCopy.Axle.transform.parent = AllAxles.transform; if (LocalCopy.ThisTileFlipAxis == TileFlipAxis.Vertical) { Vector3 Temp = new Vector3(0, 0, 90); LocalCopy.Axle.transform.SetPositionAndRotation(LocalCopy.Axle.transform.position, Quaternion.Euler(Temp)); } } } MenuMan.SetAllAxles(AllAxles); }
public void ChanceToSpawnPowerUp(BaseTile tile) { if (HasSpawnPowerUp() && !Quit) { SpawnPowerUp(tile); } }
private void CheckClick() { // Check if player clicked if (Input.GetMouseButtonDown(0)) { // Make UI (current dialogs) block raycast. if (!EventSystem.current.IsPointerOverGameObject()) { // Raycast from mouse position if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out RaycastHit clickHitInfo)) { BaseTile clicked = clickHitInfo.collider.GetComponent <BaseTile>(); // Check if the object that was hit was a tile, if so handle click if (clicked) { HandleClick(clicked); } // If raycast didn't hit an instance of BaseTile, stop showing the dialog else { ui.HideDialog(); } } // If raycast didn't hit anything, hide the dialog else { ui.HideDialog(); } } } }
public override void TileProc(int aX, int aY, ref bool refContinue) { NWField f = Field; Step(aX, aY); if (f.IsBarrier(aX, aY)) { refContinue = false; } else { BaseTile tile = f.GetTile(aX, aY); NWCreature c = (NWCreature)f.FindCreature(aX, aY); if (c != null) { string cSign = c.Entry.Sign; if (cSign.Equals("Mudman") || cSign.Equals("MudFlow")) { EffectsFactory.Deanimate(f, c, tile, PlaceID.pid_Mud); } else { if (cSign.Equals("LavaFlow")) { EffectsFactory.Deanimate(f, c, tile, PlaceID.pid_Lava); } else { if (cSign.Equals("Jagredin") || cSign.Equals("LiveRock")) { EffectsFactory.Deanimate(f, c, tile, PlaceID.pid_Rubble); } else { if (cSign.Equals("SandForm")) { EffectsFactory.Deanimate(f, c, tile, PlaceID.pid_Quicksand); } else { if (cSign.Equals("WateryForm")) { EffectsFactory.Deanimate(f, c, tile, PlaceID.pid_Water); } else { if (c.State == CreatureState.Undead) { c.Death("", null); } } } } } } } } }
public bool CheckRestrictions(BaseTile selectedTile, UnityObject _unityObject) { BaseTile tileType = selectedTile.GetComponentInChildren <BaseTile>(); if (selectedTile.State != State.Unavailable && selectedTile.State != State.Off) { if (tileType is AsphaltTile) { if (_unityObject.CanBePlacedOn().Contains(TileType.Asphalt)) { return(true); } } else if (tileType is GrassTile) { if (_unityObject.CanBePlacedOn().Contains(TileType.Grass)) { return(true); } } else if (tileType is WaterTile) { if (_unityObject.CanBePlacedOn().Contains(TileType.Water)) { return(true); } } } return(false); }
private Dictionary <MapDataFile, BaseTile[, ]> ParseMapData() { Dictionary <MapDataFile, BaseTile[, ]> dataDict = new Dictionary <MapDataFile, BaseTile[, ]>(); foreach (MapDataFile mapDataFile in MapDataFiles) { BaseTile[,] mapData = new BaseTile[MapDataFile.MapWidth, MapDataFile.MapHeight]; mapDataFile.Stream.Seek(MapDataFile.MapDataOffset, SeekOrigin.Begin); for (int y = 0; y < MapDataFile.MapHeight; y++) { for (int x = 0; x < MapDataFile.MapWidth; x++) { int offset = (int)mapDataFile.Stream.Position; MapDataFile.TileTypes typeId = (MapDataFile.TileTypes)mapDataFile.Stream.ReadByte(); if (MapDataFile.TileTypeClassMapping.ContainsKey(typeId)) { mapData[x, y] = (BaseTile)Activator.CreateInstance(MapDataFile.TileTypeClassMapping[typeId], new object[] { this, mapDataFile, offset, new Point(x, y), (PropertyChangedEventHandler)GameDataPropertyChanged }); } else { mapData[x, y] = new BaseTile(this, mapDataFile, offset, new Point(x, y), GameDataPropertyChanged); } } } dataDict.Add(mapDataFile, mapData); } return(dataDict); }
public void CreateTilesFromConfiguration(TileConfig tileConfig, UnityObject prefab) { Vector2 coordinate = tileConfig.coordinate; TileType type = tileConfig.type; State state = tileConfig.state; int tileCoordinateX = (int)coordinate.x; int tileCoordinateY = (int)coordinate.y; BaseTile tile = null; switch (type) { case TileType.Water: tile = waterTilePrefab; break; case TileType.Asphalt: tile = asphaltTilePrefab; break; case TileType.Grass: tile = grassTilePrefab; break; } InstantiateSavedTile(tileCoordinateX, tileCoordinateY, tile); InstantiateSavedUnityObject(tileCoordinateX, tileCoordinateY, prefab); SetState(tileCoordinateX, tileCoordinateY, state); }
private async Task ProcessOverrides(BaseTile tile) { switch (tile) { // Calendars use a special API that isn't (might not be?) exposed via the WebSocket API. case CalendarTile ct: // Required because for some reason, the calendar API is not available // via the "inside" supervisor API, only the "external" fully-qualified // API endpoint. var config = await ConfigStore.GetConfigAsync(); var calClient = new CalendarClient(new Uri(!string.IsNullOrWhiteSpace(config.Settings?.OverrideAssetUri) ? config.Settings.OverrideAssetUri : config.Settings.BaseUri), config.Settings.AccessToken); var state = await StatesClient.GetState(ct.EntityId); var calItems = await calClient.GetEvents(ct.EntityId); await Clients.Caller.SendCalendarInfo(ct, state, calItems); break; // Date and time are rendered server-side to verify server connection, and to enforce timezone and date format selection. case DateTile dt: var date = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(dt.TimeZoneId)); await Clients.Caller.SendDateTime(dt, date.ToString(dt.DateFormatString ?? "dddd MMMM d"), date.ToString(dt.TimeFormatString ?? "h:mm tt")); break; } }
public bool IsSpotWalkable(int x, int y) { if (!InLayerBounds(x, y)) { return(false); } BaseTile tile = Tiles[x][y]; if (tile != null) { if (tile.Walkable == false) { return(false); } } Furniture f = World.Instance.Furniture.GetFurnitureAt(x, y); if (f != null) { if (!f.Walkable) { return(false); } } return(true); }
private void Start() { //int gridSize = Constants.gridSizeHorizontal * Constants.gridSizeVertical; columns.Clear(); for (int x = 0; x < Constants.gridSizeHorizontal; x++) { GameObject newColumn = Instantiate(Resources.Load("Column")) as GameObject; TileColumn column = newColumn.GetComponent <TileColumn>(); column.Init(x); newColumn.transform.SetParent(this.transform, false); newColumn.name = "Column " + x; columns.Add(newColumn.GetComponent <TileColumn>()); for (int y = 0; y < Constants.gridSizeVertical; y++) { GameObject newTile = Instantiate(Resources.Load("Tile")) as GameObject; newTile.transform.SetParent(newColumn.transform, false); BaseTile tile = newTile.GetComponent <BaseTile>(); //int hori = i % Constants.gridSizeHorizontal; //Row //int vert = Mathf.FloorToInt(i / Constants.gridSizeHorizontal); tile.xy = new Vector2(x, y); newTile.name = "Tile (" + x + "," + y + ")"; //F.e. Tile (0,7) tile.InitRandom(); column.tiles.Add(tile); } } }
private void CheckHover() { // Make UI (current dialogs) block raycast. if (!EventSystem.current.IsPointerOverGameObject()) { // Raycast from mouse position Vector3 start = cam.ScreenPointToRay(Input.mousePosition).origin; Vector3 dir = cam.ScreenPointToRay(Input.mousePosition).direction; Debug.DrawLine(start, start + (dir * 10), Color.green); if (Physics.Raycast(start, dir, out RaycastHit hoverHitInfo)) { BaseTile hover = hoverHitInfo.collider.GetComponent <BaseTile>(); // Set the current hover object to the object that was hit (if not tile was hit, the value will be null) CurrentHover = hover; } else { CurrentHover = null; } } // Set hover to null if raycast hit nothing else { CurrentHover = null; } }
public BaseTile FindBaseTileAtPosition(Vector2 position) { List <BaseTile> allTiles = AllTilesAsBaseTile(); BaseTile targetTile = allTiles.Find(item => item.x == position.x && item.y == position.y); return(targetTile); }
private void Refill(TileColumn column, string direction) { int tilesNeeded = Constants.gridSizeVertical - column.tiles.Count; for (int i = 0; i < tilesNeeded; i++) { GameObject newTile = Instantiate(Resources.Load("Tile")) as GameObject; newTile.transform.SetParent(column.transform, false); if (direction == "top") { newTile.transform.SetAsFirstSibling(); } BaseTile tile = newTile.GetComponent <BaseTile>(); tile.InitRandom(); if (direction == "top") { column.tiles.Insert(0, tile); } else { column.tiles.Add(tile); } } foreach (BaseTile tile in column.tiles) { tile.transform.name = "Tile (" + column.number + ", " + column.tiles.IndexOf(tile) + ")"; //F.e. Tile (0,7) tile.xy = new Vector2(column.number, column.tiles.IndexOf(tile)); } }
public List <BaseTile> GetAdjacentTiles(int casts = 12) { List <BaseTile> result = new List <BaseTile>(); float perStep = (2.0f * Mathf.PI) / casts; for (float f = 0; f < 2.0f * Mathf.PI; f += perStep) { // angle is f, turn that into a vector Vector3 direction = new Vector3(); direction.x = Mathf.Sin(f); direction.z = Mathf.Cos(f); var hits = Physics.RaycastAll(transform.position, direction); float closestDist = Mathf.Infinity; BaseTile closestTile = null; foreach (var hit in hits) { if (hit.distance < closestDist && hit.collider.gameObject != this.gameObject) { closestDist = hit.distance; closestTile = hit.collider.gameObject.GetComponent <BaseTile>(); } } if (closestTile != null && !result.Contains(closestTile)) { result.Add(closestTile); } } return(result); }
private void Collider_OnCollision(object sender, CollisionEventArgs result) { BaseTile tile = result.CollidingObject as BaseTile; GameObject gameObject = result.CollidingObject as GameObject; if (tile != null && brain.CurrentState != RunAwayFromTile) { stateTime = 0; lastTileCollidedWith = tile; brain.PushState(RunAwayFromTile); } else if (gameObject != null) { stateTime = 0; lastObjectCollidedWith = gameObject; Animal animal = gameObject as Animal; if (animal != null) { if (animal.Dataset.Type == "Dog" && brain.CurrentState != PlayWithOtherDog) { lastDogCollidedWith = animal; brain.PushState(PlayWithOtherDog); } } else if (brain.CurrentState != RunAwayFromOtherObject) { brain.PushState(RunAwayFromOtherObject); } } }
public void GenerateGrid(int rows = -1, int columns = -1) { ClearGrid(); if (rows > 0) { m_rows = rows; } if (columns > 0) { m_columns = columns; } m_GridArray = new BaseTile[m_rows, m_columns]; for (int r = 0; r < m_rows; r++) { for (int c = 0; c < m_columns; c++) { GameObject newTile = GameObject.Instantiate(_tilePrefab, GridRoot.transform); newTile.name = "Tile " + r + ", " + c; BaseTile tile_ref = newTile.GetComponent <BaseTile>(); tile_ref.InitializeTile(r, c); m_GridArray[r, c] = tile_ref; } } }
public bool PlaceGameObjectOnSelectedTile(BaseTile selectedTile, UnityObject _unityObject) { if (CheckRestrictions(selectedTile, _unityObject) && IsTileAvailable(selectedTile, _unityObject)) { UnityObject clone = Instantiate(_unityObject, selectedTile.transform); selectedTile.unityObject = clone; //deactivate surrounding Tiles regarding Objects size Vector3 sizeInTiles = _unityObject.SizeInTiles(); zoneSizeX = (int)sizeInTiles.x; zoneSizeY = (int)sizeInTiles.z; if (adminAccess) { this.UpdateZoneOfTiles(selectedTile.Coordinate, State.Available, State.Off); } else { this.UpdateZoneOfTiles(selectedTile.Coordinate, State.Available, State.Unavailable); } return(true); } return(false); }
/// <summary> /// Initializes a new instance of the <see cref="TileItem"/> class. /// </summary> /// <param name="tile"> /// The tile. /// </param> public TileItem(BaseTile tile) { this.Id = tile.TemplateType; this.Tile = tile; this.Xml = System.Xml.Linq.XDocument.Parse(tile.ToString()).ToString(); this.Description = tile.GetDescription(); }
public List <BaseTile> OtherTilesToExplode(TileGridController grid) { List <BaseTile> toDestroy = new List <BaseTile>(); Vector2[] positions; positions = new Vector2[8]; Debug.Log("Area destruction around " + x + ", " + y); positions[0] = new Vector2(x - 1f, y - 1f); positions[1] = new Vector2(x, y - 1f); positions[2] = new Vector2(x + 1f, y - 1f); positions[3] = new Vector2(x - 1f, y); positions[4] = new Vector2(x + 1f, y); positions[5] = new Vector2(x - 1f, y + 1f); positions[6] = new Vector2(x, y + 1f); positions[7] = new Vector2(x + 1f, y + 1f); for (int i = 0; i < positions.Length; i++) { BaseTile baseTile = grid.FindBaseTileAtPosition(positions[i]); if (baseTile && !baseTile.isBeingDestroyed) { toDestroy.Add(baseTile); } } return(toDestroy); }
/// <summary> /// Sets the pixels corresponding to the tile in its current surroundings. None of the parameters can be null apart from 'tile'. /// Caches the operation so future calls with the same BaseTile will be very quick. /// </summary> public void SetTile(BaseTile tile, TileLayer layer, int globalX, int globalY, int x, int y) { if (tile == null) { SetTile(GetTransparentTile(), x, y); } else { int index = tile.GetAutoIndex(layer, globalX, globalY); if (tile.RenderData.IsCached(index)) { // Already cached, just paint. SetTile(tile.RenderData.GetCachedPixels(index), x, y); } else { // Need to grab and flip the pixels, the store them again. tile.RenderData.SetCachedPixels(index, GetColours(tile.RenderData.GetSprite(index), true, true)); // Now paint the tile. SetTile(tile.RenderData.GetCachedPixels(index), x, y); } } }
/// <summary> /// Parse the given lines into the map /// </summary> /// <param name="lines">The lines to create the map from</param> private IEnumerable <BaseTile> ParseLines(string[] lines) { // Setup from the first two lines Name = lines[0]; MapNumber = int.Parse(lines[1]); int rows = lines.Length - 2; int yOffset = rows < MagicNumbers.TILEVISUALROWS ? MagicNumbers.TILEVISUALROWS - rows : 0; int maxCols = 0; // Setup all tiles based on the x,y location for (int i = 2; i < lines.Length; i++) { int row = i - 2 + yOffset; string line = lines[i]; maxCols = Math.Max(maxCols, line.Length); for (int j = 0; j < line.Length; j++) { int col = j; BaseTile tile = Generate(line[j]); if (tile != null) { tile.Top = MagicNumbers.TILESIZE * row + tile.TopOffset; tile.Left = MagicNumbers.TILESIZE * col + tile.LeftOffset; yield return(tile); } } } // Set the height and width MapHeight = MagicNumbers.TILESIZE * (rows + yOffset); MapWidth = MagicNumbers.TILESIZE * maxCols; }
void GenerateTiles() { RemoveOldTiles(); SetBackgroundDimensions(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { BaseTile tile = GameObject.Instantiate <BaseTile>(tilePrefab); tile.transform.position = GetTileGlobalPosition(i, j); tile.transform.rotation = Quaternion.identity; tile.transform.localScale = GetTileSize(); tile.transform.parent = this.transform; TrimName(tile.gameObject); tile.SetViewportPosition(GetViewportPosition(i, j)); allTiles.Add(tile); } } if (onCreateTiles != null) { onCreateTiles(allTiles.ToArray()); } }
protected async Task <IActionResult> SaveBaseTile(IConfigStore store, BaseTile tile) { await store.ManipulateConfig(c => { if (!string.IsNullOrWhiteSpace(Request.Form["originalName"])) { var existing = c.Tiles.FirstOrDefault(t => t.Name == Request.Form["originalName"]); if (existing == null) { TempData.AddError($"Unable to update tile with original name '{Request.Form["originalName"]}'."); } var i = c.Tiles.IndexOf(existing); c.Tiles.RemoveAt(i); c.Tiles.Insert(i, tile); } else { c.Tiles.Add(tile); } }); TempData.AddSuccess($"Successfully saved {tile.Type} tile '{tile.Name}'."); return(RedirectToAction("Index", "AdminTile")); }
private bool UpdateTileState(BaseTile tile, State state1, State state2) { if (tile.State == state1) { //Changing State Activ or inactive if (state2 == State.Off || state2 == State.Available && state1 == State.Off || state2 == State.Unavailable || state2 == State.Available && state1 == State.Unavailable) { tile.GetComponentInChildren <Renderer>().material.color *= zoneBrightness; } //changing to hovered else if (state2 == State.Hovered) { tile.GetComponentInChildren <Renderer>().material.color += HOVERINGCOLOR; } //changing back from hovered else if (state2 == State.Available && state1 == State.Hovered) { tile.GetComponentInChildren <Renderer>().material.color -= HOVERINGCOLOR; } //appliying changes tile.State = state2; return(true); } return(false); }
public static void TeleportTo(BaseUnit unit, BaseTile sourceTile, BaseTile destinationTile) { Vector3 position = destinationTile.transform.position; position.y = unit.transform.position.y; unit.transform.position = position; HandleOccupy(unit, sourceTile, destinationTile); HandleArrive(unit, sourceTile, destinationTile); }
protected override void OnArrived(BaseUnit unit, BaseTile previousTile) { base.OnArrived(unit, previousTile); if (IsPortalTile) { TeleportUnit(unit, previousTile, DestinationTeleportTile); } }
protected override void OnArrived(BaseUnit unit, BaseTile previousTile) { base.OnArrived(unit, previousTile); if (previousTile == DestinationTile || DestinationTile == null) // Came from the other portal return; if (!DestinationTile.CanWalkOn(unit)) return; BaseTile.TeleportTo(unit, this, DestinationTile); if (unit is AvatarUnit) { AvatarUnit avatar = (AvatarUnit) unit; avatar.EmptyMoveQueue(); } }
protected override void OnArrived(BaseUnit unit, BaseTile previousTile) { base.OnArrived(unit, previousTile); BaseTile tile = null; while(tile == null) { int x = Random.Range(0, GridManager.GetLength(0)); int y = Random.Range(0, GridManager.GetLength(1)); tile = GridManager.GetTile(x, y); if (tile != null && tile != this && tile.CanWalkOn(unit)) // This should be solved better... A "is tile valid" check.. tile = null; } BaseTile.TeleportTo(unit, previousTile, tile); }
protected override void OnLeaved(BaseUnit unit, BaseTile nextTile) { if (UseStaticEventMethods && (objectsToNotify_1.Any() || objectsToNotify_2.Any())) { foreach (EventListener el in objectsToNotify_1) { el.ReceiveEventMethod(StaticLeaveMethod_1, this.EventGetGridManager()); //Sends the gridmanager for objects who was not active at game start } foreach (EventListener el in objectsToNotify_2) { el.ReceiveEventMethod(StaticLeaveMethod_2, this.EventGetGridManager()); //Sends the gridmanager for objects who was not active at game start } } else { foreach (EventListener el in objectsToNotify_1) el.ReceiveEvent(LeaveMessage); } }
protected bool CanMove(BaseTile tile, int xDir, int zDir) { bool canMove = true; foreach (BaseUnit u in tile.OccupyingUnits(unit)) { if (canMove) { canMove = unit == u || u.CanWalkOn(gameObject.tag); // You can walk here if it's to yourself or to a "walkable" unit. if (!canMove && isPusher) { if (isAvatarMover == false) { // If not a walkable, check if you are a 'Pusher' and it can be moved. BaseMover mover = u.GetComponent<BaseMover>(); if (mover != null) { canMove = mover.TryMove(xDir, zDir); } } else { if (currentAvatarUnit.Strength >= u.Weight) { // If not a walkable, check if you are a 'Pusher' and it can be moved. currentAvatarUnit._stateMachine.ChangeState((int)AvatarUnit.AvatarState.Pushing); //Starts push animation BaseMover mover = u.GetComponent<BaseMover>(); if (mover != null && mover.canBePushed) { canMove = mover.TryMove(xDir, zDir); } } } } } unit.OnCollided(u); u.OnCollided(unit); } return canMove && tile.CanWalkOn(unit); }
public BaseTile getClosestOpenTile(BaseTile ToCheck, TeamInfo T, GetLocalTiles locals) { List<BaseTile> open = locals(ToCheck, T); BaseTile returnable = null; int minVal = int.MaxValue; open.ForEach(delegate(BaseTile obj) { if(ToCheck.calcHueristic(ToCheck, obj) < minVal){ returnable = obj; minVal = ToCheck.calcHueristic(ToCheck, obj);} }); return returnable; }
public DirectionEnum? getRelation(BaseTile toCheck) { if(toCheck.brdXPos == brdXPos && toCheck.brdYPos == brdYPos+1) return DirectionEnum.North; if(toCheck.brdXPos == brdXPos && toCheck.brdYPos == brdYPos-1) return DirectionEnum.South; if(toCheck.brdXPos == brdXPos+1 && toCheck.brdYPos == brdYPos) return DirectionEnum.East; if(toCheck.brdXPos == brdXPos-1 && toCheck.brdYPos == brdYPos) return DirectionEnum.West; return null; }
public static List<BaseTile> getLocalNonTiles(BaseTile current, TeamInfo T) { return null; }
public static List<BaseTile> getLocalSameTeamTiles(BaseTile current, TeamInfo T) { List<BaseTile> returnable = current.getLocalTiles(); returnable.RemoveAll(x => x.owningTeam == null); returnable.RemoveAll(x => x.owningTeam.teamNumber != T.teamNumber); return returnable; }
public static void reconstructPath(BaseTile start, AStarholder a, List<AStarholder> returnable) { if(a!= null){ if(a.current.Ident == start.Ident){ returnable.Add(a); }else{ reconstructPath(start, a.parent, returnable); returnable.Add(a); } } }
protected override void OnLeaved(BaseUnit unit, BaseTile nextTile) {}
protected abstract void OnLeaved(BaseUnit unit, BaseTile sourceTile);
protected virtual void OnArrived(BaseUnit unit, BaseTile destinationTile) { if (unit.Weight > Durability) { GridManager.RemoveTile(this); Destroy(this.gameObject); unit.InitStartFallingRoutine(); } }
//Used by the teleport of portal tiles protected void TeleportUnit(BaseUnit unit, BaseTile previousTile, BaseTile destinationTeleportTile) { if (previousTile == destinationTeleportTile || destinationTeleportTile == null)// Came from the other portal { return; } if (!destinationTeleportTile.CanWalkOn(unit)) { return; } BaseTile.TeleportTo(unit, this, destinationTeleportTile); if (unit is AvatarUnit) { AvatarUnit avatar = (AvatarUnit)unit; avatar.EmptyMoveQueue(); } }
public static void HandleOccupy(BaseUnit unit, BaseTile sourceTile, BaseTile destinationTile) { if (sourceTile != null) sourceTile.Unoccupy(unit); if (destinationTile != null) destinationTile.Occupy(unit); }
public static void HandleArrive(BaseUnit unit, BaseTile sourceTile, BaseTile destinationTile) { if (sourceTile != null) sourceTile.Leave(unit, destinationTile); if (destinationTile != null) destinationTile.Arrive(unit, sourceTile); }
public AStarholder(BaseTile current, AStarholder parent) { this.current = current; this.parent = parent; }
public TileClickedEvent(Transform tile, BaseTile basetile) { Tile = tile; baseTile = basetile; }
private void Leave(BaseUnit unit, BaseTile destinationTile) { unit.OnLeaved(this); OnLeaved(unit, destinationTile); }
public void findEdgesInner(ref bool northFound, ref bool southFound, ref bool eastFound, ref bool westFound, Dictionary<int, BaseTile> visited, GetLocalTiles LocalFunction, BaseTile current) { if(!visited.ContainsKey(current.Ident)){ visited.Add(current.Ident, current); if(current.North == null){ northFound = true; } if(current.West == null){ westFound = true; } if(current.East == null){ eastFound = true; } if(current.South == null){ southFound = true; } List<BaseTile> tilesToVisit = LocalFunction(current, controllingTeam); foreach (BaseTile B in tilesToVisit){ findEdgesInner(ref northFound, ref southFound, ref eastFound, ref westFound, visited, LocalFunction, B); } } }
private void Arrive(BaseUnit unit, BaseTile sourceTile) { unit.OnArrived(this, _previousUnits); foreach (BaseUnit u in _previousUnits) u.OnArrivedToMe(unit); _previousUnits.Clear(); OnArrived(unit, sourceTile); }
public int calcHueristic(BaseTile start, BaseTile end) { int manhattan = Mathf.Abs(end.brdXPos - start.brdXPos) + Mathf.Abs(end.brdYPos - start.brdYPos); return manhattan*4; //Average tile cost; }
public override void BehaveOnCurrentTile(BaseTile tile) { Instantiate(this, tile.TransformCache.position, Quaternion.identity); }
/// <summary> /// STUB method /// </summary> /// <returns>The local open tiles.</returns> /// <param name="currentAp">Current ap.</param> public static List<BaseTile> getLocalTraversableTiles(BaseTile current, TeamInfo T) { // if( List<BaseTile> returnable = current.getLocalTiles(); returnable.RemoveAll(x => x.currentType == TileTypeEnum.water); return returnable; }
public Ground(BaseTile BT) { this.BT = BT; }
public static List<AStarholder> aStarSearch(BaseTile start, BaseTile end, int currentAp, GetLocalTiles LocalMethod, TeamInfo team) { Dictionary<int, AStarholder> closedSet = new Dictionary<int, AStarholder>(); Dictionary<int, AStarholder> openSet = new Dictionary<int, AStarholder>(); AStarholder current = new AStarholder(start, null); current.hurVal = current.current.calcHueristic(current.current, end); //current.apAtThisTurn = currentAp; current.pathCostToHere = 0; openSet.Add(current.current.Ident, current); List<AStarholder> returnable = new List<AStarholder>(); while (openSet.Count >0){ openSet.Remove(current.current.Ident); closedSet.Add(current.current.Ident, current); if(current.current.Ident == end.Ident){ BaseTile.reconstructPath(start, current, returnable); return returnable;} List<BaseTile> listies =LocalMethod(current.current, team); listies.ForEach(delegate (BaseTile bt){ if(!closedSet.ContainsKey(bt.Ident)){ AStarholder newOpen = new AStarholder(bt, current); newOpen.hurVal = newOpen.current.calcHueristic(newOpen.current, end); //newOpen.apAtThisTurn = current.apAtThisTurn - newOpen.current.MoveCost; newOpen.pathCostToHere = newOpen.current.MoveCost + current.pathCostToHere; if(openSet.ContainsKey(bt.Ident)){ if(openSet[bt.Ident].fVal > newOpen.fVal){ openSet[bt.Ident] = newOpen; } } else{ openSet.Add (bt.Ident, newOpen); } } }); current = null; foreach(KeyValuePair<int, AStarholder> val in openSet){ if(current == null){ current = val.Value; } if(current.fVal > val.Value.fVal){ current = val.Value; } } } //Ran out of moves, find the lowest HurVal and return path to it AStarholder finalNode = null; foreach(KeyValuePair<int, AStarholder> val in openSet){ if(finalNode == null){ finalNode = val.Value; } if(current.fVal > val.Value.fVal){ finalNode = val.Value; } } BaseTile.reconstructPath(start, finalNode, returnable); return returnable; }
// set each order's command and go-to position void SetOrderValues(List<Vector3> position, BaseTile tile) { // determine what sprite to use for representation of command Sprite curSprite = nullSprite; if(activeCommand == OrderType.Hold){ curSprite = holdSprite; }else if(activeCommand == OrderType.Move){ curSprite = moveSprite; }else if(activeCommand == OrderType.Attack){ curSprite = attackSprite; } if(activeOrder == 1){ if(activeCommand == OrderType.Move){ if(nextTile == tile){ // do nothing }else{ // set new nextTile nextTile = tile; // and clear other orders orderTwoA = OrderType.Null; orderTwoAPosition = null; orderTwoAButton.GetComponent<Image>().sprite = nullSprite; orderTwoB = OrderType.Null; orderTwoBPosition = null; orderTwoBButton.GetComponent<Image>().sprite = nullSprite; } } // set values of orderOne orderOne = activeCommand; orderOnePosition = position; // change sprite to indicate order's command orderOneButton.GetComponent<Image>().sprite = curSprite; // move the indicator to the specific tile with appropriate image orderOneIndicator.GetComponent<SpriteRenderer>().sprite = curSprite; orderOneIndicator.transform.position = tile.transform.position; }else if(activeOrder == 2){ // set values of orderTwoA orderTwoA = activeCommand; orderTwoAPosition = position; // change sprite to indicate order's command orderTwoAButton.GetComponent<Image>().sprite = curSprite; // move the indicator to the specific tile with appropriate image orderTwoAIndicator.GetComponent<SpriteRenderer>().sprite = curSprite; orderTwoAIndicator.transform.position = tile.transform.position; }else if(activeOrder == 3){ // set values of orderTwoB orderTwoB = activeCommand; orderTwoBPosition = position; // change sprite to indicate order's command orderTwoBButton.GetComponent<Image>().sprite = curSprite; // move the indicator to the specific tile with appropriate image orderTwoBIndicator.GetComponent<SpriteRenderer>().sprite = curSprite; orderTwoBIndicator.transform.position = tile.transform.position; } // display the indicators as they can be shown now ShowIndicators(true); // if the unit is ordered out, raise event if(orderOne != OrderType.Null && orderTwoA != OrderType.Null && orderTwoB != OrderType.Null){ Events.instance.Raise( new UnitOrderedOutEvent (transform)); }else{// otherwise, show the UI to choose the remaining orders // show the UI for the unit again orderUI.SetActive(true); // with the appropriate clickable things CommandsInteractable(false); OrdersInteractable(true); } }