public void GenerateTowerPreview(int towerLevel) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity); Vector3Int? spawnTile = GridManager.Grid.GetSpawnLocationTile(hit); if (spawnTile != null) { Vector3 pos = GridManager.Grid.GetCentreOfTile((Vector3Int)spawnTile); //draw preview with radius at suggested location transform.position = pos; transform.localScale = EntityFactory.Factory.GetTowerScale(); m_spriteRend.sprite = EntityFactory.Factory.GetTowerSprite(); m_spriteRend.color = EntityFactory.Factory.GetTowerColor(towerLevel); float towerRadius = EntityFactory.Factory.GetTowerRadius(towerLevel); for (int i = 0; i < m_circleSegCount; i++) { m_lineRend.SetPosition(i, ComputeSegment(i * m_angleStep, towerRadius)); } gameObject.SetActive(true); } else { //if no spawnTile returned, then the user is not hovering over a valid tile //therefore no preview should be shown gameObject.SetActive(false); } }
public int AddObstacle(Transform t, Vector3Int?cell = null) { Vector3Int cell_value = cell ?? g.LocalToCell(t.localPosition); obstacle_blocks.Add(cell_value, t); return(obstacle_blocks.Count); }
public virtual void Initialize(Vector3Int?gridPosition = null) { _initialized = true; // Set the GridPosition if (gridPosition.HasValue) { m_GridPosition = gridPosition.Value.ToVector2IntXY(); } else { // Set the grid position based on the world position m_GridPosition = GetGridPosFromWorldPosition(); } // Check if there is a tile at the GridPosition if (GridManager.Instance.ExistsTileAtPosition(m_GridPosition)) { GridTile gridTile = GridManager.Instance.GetGridTileAtPosition(m_GridPosition); SetCurrentGridTile(gridTile); // Update the current tile on this GridObject AddToTile(gridTile); // Add this Gridobject to the occupant list on the target Gridtile } else { Debug.Log("There is not a tile at this GridObject's GridPosition"); } // Add this GridObject to the GridManager's GridObject List GridManager.Instance.AddGridObject(this); // Get the movement blockers for this GridObject m_MovementBlockers = GetComponents <MovementBlocker>().ToList(); }
private void Update() { if (GameState.GetInstance()._CurrentUIState != UIIngameState.GAME) { crossTilemap.ClearAllTiles(); return; } // Get the tile we're looking at // Render a selection square at it var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3Int currentPos = Vector3Int.FloorToInt(mousePos); if (lastPos != currentPos) { lastPos = currentPos; crossTilemap.ClearAllTiles(); crossTilemap.SetTile(currentPos, crossTile); } if (Input.GetMouseButtonDown(0)) { GameState.GetInstance()._ZoneState.DestroyEntity(new Vector2Int(currentPos.x, currentPos.y)); } }
private void Update() { if (!IsPlanningExplosiveShot) { return; } if (!GameManager.Instance.PlanConstructionManager.GetHoverPosition( out Vector3Int tilePosition, target => Tilemaps.Ground.HasTile(target) || Tilemaps.OuterEdge.HasTile(target) )) { if (_lastHoverTile == null) { return; } Tilemaps.Highlights.ClearAllTiles(); _lastHoverTile = null; return; } if (tilePosition != _lastHoverTile) { _lastHoverTile = tilePosition; Tilemaps.Highlights.ClearAllTiles(); DisplayExplosiveShotArea(tilePosition); } }
void Update() { if (Input.GetMouseButton(0)) { Vector3 click = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3Int p = grid.WorldToCell(click); if (p != prevClickPos) { prevClickPos = p; //tilemap.SetTile(p, currentTile); UpdateCells(p); } } if (Input.GetMouseButton(1)) { Vector3 click = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3Int p = grid.WorldToCell(click); //tilemap.SetTile(p, null); if (p != prevClickPos) { prevClickPos = p; UpdateCells(p, true); } } if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1)) { Debug.Log("mouse up"); prevClickPos = null; } }
public int AddSelectable(Transform t, Vector3Int?cell = null) { Vector3Int cell_value = cell ?? g.LocalToCell(t.localPosition); selectable_objects.Add(cell_value, t); return(selectable_objects.Count); }
private void Update() { var currentTargetCell = getTargetCell(target.position); if (!currentCell.HasValue || currentTargetCell != currentCell.Value) { const int generationExtent = 1; for (var i = -generationExtent; i <= generationExtent; i++) { for (var j = -generationExtent; j <= generationExtent; j++) { for (var k = -generationExtent; k <= generationExtent; k++) { var c = currentTargetCell + new Vector3Int(i, j, k); generationQueue.Enqueue(c); } } } currentCell = currentTargetCell; } if (generationQueue.Count != 0) { if (!generator.isBusy) { Generate(generationQueue.Dequeue()); } } }
public Node(Vector3Int position, Vector3Int?parent, float heuristic, int pathLength) { this.position = position; this.parent = parent; this.pathLength = pathLength; cost = pathLength + heuristic; }
/** * Checks if task performer has reached task target. Does not check target availability (map area). * Returns fail if checked from out of map. */ public ActionTargetStatusEnum check(EcsEntity performer) { Vector3Int performerPosition = performer.pos(); Vector3Int?target = getPosition(); if (!target.HasValue) { return(READY); // target without position } int distance = getDistance(performerPosition, target.Value); if (distance > 1) { return(WAIT); // target not yet reached } switch (type) { case ActionTargetTypeEnum.EXACT: return(distance == 0 ? READY : WAIT); case ActionTargetTypeEnum.NEAR: return(distance == 1 ? READY : STEP_OFF); case ActionTargetTypeEnum.ANY: return(READY); // distance is 0 or 1 here } return(FAIL); }
public Vector3Int?GetPositionOfTheNeighbourIfExists(Vector3 gridPosition, Direction direction) { Vector3Int?neighbourPosition = Vector3Int.FloorToInt(gridPosition); switch (direction) { case Direction.Up: neighbourPosition += new Vector3Int(0, 0, cellSize); break; case Direction.Right: neighbourPosition += new Vector3Int(cellSize, 0, 0); break; case Direction.Down: neighbourPosition += new Vector3Int(0, 0, -cellSize); break; case Direction.Left: neighbourPosition += new Vector3Int(-cellSize, 0, 0); break; } var index = CalculateGridIndex(neighbourPosition.Value); if (CheckIndexValidity(index) == false) { return(null); } return(neighbourPosition); }
public static bool CheckIfNeighborHasRoadWithinDictionary(Vector3Int? neighborPosition, Dictionary<Vector3Int, GameObject> structuresToBeModified) { if (structuresToBeModified == null) return false; return structuresToBeModified.ContainsKey(neighborPosition.Value); }
public static void scan(Vector3Int?min = null, Vector3Int?size = null) { if (envmap_ == null) { envmap_ = new EnvMap(scanSize.x * scanSize.y * scanSize.z * 2); } var cmin = min ?? scanOffset; var csize = size ?? scanSize; for (int x = cmin.x; x < cmin.x + csize.x; ++x) { for (int y = cmin.y; y < cmin.y + csize.y; ++y) { for (int z = cmin.z; z < cmin.z + csize.z; ++z) { var area = new Area(new Vector3(x, y, z)); var res = looka(area); if (envmap_.ContainsKey(area)) { envmap_[area] = res; } else { envmap_.Add(area, res); } } } } //scan_impl(min ?? scanOffset, size ?? scanSize); }
/// <summary> /// Finds the adjacent tile coordinate to the given tile coordinate that is the furthest /// from the given reference tile coordinate. /// </summary> /// <param name="boundaryMap"> /// A two-dimentional bool array created from <see cref="CreateBoundaryMap"/>. /// </param> /// <param name="tileCoordinate"> /// The tile coordinate by which adjacent tile coordinates will be checked. /// </param> /// <param name="referenceTileCoordinate"> /// The tile coordinate from which the distance will be calculated to tile coordinates /// adjacent to <see cref="tileCoordinate"/>. /// </param> /// <returns> /// The adjacent tile coordinate that is the furthest from the reference tile coordinate /// </returns> public static Vector3Int?GetFurthestAdjacentTileCoordinate(bool[,] boundaryMap, Vector3Int tileCoordinate, Vector3Int referenceTileCoordinate) { Vector3Int? furthestAdjacentTileCoordinate = null; List <Vector3Int> adjacentCandidateTileCoordinates = new List <Vector3Int>(); adjacentCandidateTileCoordinates.Add(tileCoordinate + new Vector3Int(0, 1, 0)); // Up adjacentCandidateTileCoordinates.Add(tileCoordinate + new Vector3Int(1, 0, 0)); // Right adjacentCandidateTileCoordinates.Add(tileCoordinate + new Vector3Int(0, -1, 0)); // Down adjacentCandidateTileCoordinates.Add(tileCoordinate + new Vector3Int(-1, 0, 0)); // Left float furthestDistance = -1; float candidateDistance; foreach (Vector3Int candidateTileCoordinate in adjacentCandidateTileCoordinates) { candidateDistance = (candidateTileCoordinate - referenceTileCoordinate).magnitude; // We have to negate the y value because SuperTiled2Unity uses negative y tile // coordinates but the y index in the boundary map needs to be positive if (candidateDistance > furthestDistance && boundaryMap[candidateTileCoordinate.x, -candidateTileCoordinate.y]) { furthestAdjacentTileCoordinate = candidateTileCoordinate; furthestDistance = candidateDistance; } } return(furthestAdjacentTileCoordinate); }
public void ReplaceChild(Chunk currentChunk, Chunk newChunk) { Vector3Int?chunkPosition = null; foreach (KeyValuePair <Vector3Int, Chunk> pair in _children) { if (pair.Value == currentChunk) { chunkPosition = pair.Key; break; } } if (chunkPosition != null) { _children[(Vector3Int)chunkPosition] = newChunk; if (newChunk is ChunkWithGeometry geometryChunk) { OnChildUnited(geometryChunk); } else if (newChunk is ChunkWithChunks chunksChunk) { OnChildDivided(chunksChunk); } } }
public Honeycomb SpawnCorrupted(Vector3Int? pos = null) { pos = pos ?? GetFreeTilePosition(); var c = PlaceTile(pos.Value, true); return c; }
private void DirectClosestStationIndicator() { if (Map.Stations.Count == 0) { ClosestStationIndicator.SetActive(false); } else { Vector3Int?closest = null; float minDist = 0; Vector3Int playerPosition = Player.Position + Map.TopLeft; foreach (Vector3Int station in Map.Stations) { float tmpDist = Vector3Int.Distance(playerPosition, station); if (closest != null && !(tmpDist < minDist)) { continue; } closest = station; minDist = tmpDist; } if (closest == null) { return; } float angle = Mathf.Atan2(closest.Value.x - playerPosition.x, playerPosition.y - closest.Value.y); angle = angle * Mathf.Rad2Deg; ClosestStationIndicator.transform.eulerAngles = new Vector3(0, 0, angle + ClosestStationIndicatorOffset); } StationsLeftText.text = Map.Stations.Count.ToString(); }
public Block Create(Vector3Int at, Vector3Int?from = null) { Block block; if (!map.TryGetValue(at, out block)) { block = new Block(); block.Tile = at; Blocks.Add(block); map.Add(at, block); if (from != null) { var before = At(from.Value); if (before != null) { for (int i = 0; i < Faces.Length; i++) { block.Faces[i] = before.Faces[i]; } } } } return(block); }
/// <summary> /// Efficient way of iterating through the register tiles at a particular position which /// also is safe against modifications made to the list of tiles while the action is running. /// The limitation compared to Get<> is it can only get RegisterTiles, but the benefit is it avoids /// GetComponent so there's no GC. The OTHER benefit is that normally iterating through these /// would throw an exception if the RegisterTiles at this position were modified, such as /// being destroyed are created within the specified action. This method uses a locking mechanism to avoid /// such issues - it's safe to add / remove register tiles. /// </summary> /// <param name="localPosition"></param> /// <returns></returns> public void ForEachSafe(IRegisterTileAction action, Vector3Int localPosition) { if (lockedPosition != null && lockedPosition != localPosition) { Logger.LogErrorFormat("Tried to lock tile at position {0} while position {1} is currently locked." + " TileList only supports locking one position at a time. Please add this locking capability" + " to TileList if it is really necessary. Action will be skipped", Category.Matrix, localPosition, lockedPosition); return; } lockedPosition = localPosition; foreach (var registerTile in Get(localPosition)) { action.Invoke(registerTile); } lockedPosition = null; foreach (var queuedOp in queuedOps) { if (queuedOp.Remove) { Remove(queuedOp.Position, queuedOp.RegisterTile); } else { Add(queuedOp.Position, queuedOp.RegisterTile); } } queuedOps.Clear(); }
void Update() { if (EventSystem.current.IsPointerOverGameObject()) { return; } if (Input.GetMouseButton(0)) { Vector3 click = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3Int p = grid.WorldToCell(click); if (p != prevClickPos) { prevClickPos = p; if (addingSpikes) { spikes.SetTile(p, currentTile); } else { tilemap.SetTile(p, currentTile); } } } if (Input.GetMouseButton(1)) { Vector3 click = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector3Int p = grid.WorldToCell(click); tilemap.SetTile(p, null); spikes.SetTile(p, null); } if (Input.GetMouseButtonUp(0)) { prevClickPos = null; } }
public int AddLevelBlock(Transform t, Vector3Int?cell = null) { Vector3Int cell_value = cell ?? g.LocalToCell(t.localPosition); level_blocks.Add(cell_value, t); return(level_blocks.Count); }
public IEnumerator Push(WorldUtils.Direction direction, int distance) { TilemapNavigator navigator = TilemapNavigator.Instance; Vector3Int step = new Dictionary <WorldUtils.Direction, Vector3Int> { { WorldUtils.Direction.Up, Vector3Int.up }, { WorldUtils.Direction.Down, Vector3Int.down }, { WorldUtils.Direction.Left, Vector3Int.left }, { WorldUtils.Direction.Right, Vector3Int.right }, }[direction]; Vector3Int?positionAfterPush = null; for (int i = 1; i <= distance; i++) { Vector3Int testedSpot = CellPosition + step * i; if (navigator.IsTileWalkable(testedSpot) && !navigator.IsTileTaken(testedSpot)) { positionAfterPush = testedSpot; } else { break; } } if (positionAfterPush.HasValue) { yield return(StartCoroutine(Move(positionAfterPush.Value, 15, true))); } }
void TakeStep() { Vector2 target = HexEngine.instance.GetWorldPosition(Step.Value); transform.position = Vector2.MoveTowards(transform.position, target, 1f * Time.deltaTime); if (transform.position.x > target.x) { transform.localScale = new Vector2(1, 1); } else { transform.localScale = new Vector2(-1, 1); } if (Vector2.Distance(target, transform.position) < 0.01f) { Step = null; if (Path.Count == 0) { HexEngine.instance.Spaces[transform.ToGridVector3Int()] = false; } } }
private IEnumerator CardSelectTileRoutine(List <Vector3Int> tiles, SelectTileDel SelectTileFunction) { GridHelper.SetGroundTilesColor(tiles, GridHelper.spawnTileColor); Vector3Int?selectedTile = null; while (true) { if (Input.GetMouseButtonDown(0)) { Vector3Int mouseCoords = MouseCoords(); if (!GridHelper.TileInList(mouseCoords, tiles)) { break; } selectedTile = mouseCoords; break; } yield return(null); } GridHelper.SetGroundTilesColor(tiles, Color.white); SelectTileFunction(selectedTile != null && GridHelper.groundTilemap.HasTile(selectedTile.Value) ? selectedTile : null); }
private void DrawGizmos() { if (drawGridGeneratorGizmos) { DrawGridGeneratorGizmos(); } if (drawGridNodeGizmos || drawConnectionGizmos) { if (blockedNodes == null) { return; } Camera cam = FindObjectOfType <Camera>(); Vector3?worldPos = ScreenToWorldPoint(cam); if (worldPos == null) { return; } Vector3Int?nodeIdAttempt = gridGenerator.GridNodeIdFromWorldPosition((Vector3)worldPos); if (nodeIdAttempt == null) { return; } Vector3Int nodeId = (Vector3Int)nodeIdAttempt; int minX = Mathf.Max(0, nodeId.x - nodesAroundMouse.x); int maxX = Mathf.Min(gridGenerator.gridSize.x, nodeId.x + nodesAroundMouse.x); int minY = Mathf.Max(0, nodeId.y - nodesAroundMouse.y); int maxY = Mathf.Min(gridGenerator.gridSize.y, nodeId.y + nodesAroundMouse.y); int minZ = Mathf.Max(0, nodeId.z - nodesAroundMouse.z); int maxZ = Mathf.Min(gridGenerator.gridSize.z, nodeId.z + nodesAroundMouse.z); for (int floor = minY; floor <= maxY; floor++) { for (int row = minZ; row <= maxZ; row++) { for (int col = minX; col <= maxX; col++) { Vector3 pos = Vector3.Scale(new Vector3(col, floor, row), gridGenerator.nodeSize) + gridGenerator.gridStart; Vector3 size = gridGenerator.nodeSize; Collider[] colliders = Physics.OverlapBox(pos, size / 2.001F, Quaternion.identity, gridGenerator.layerObstacles); blockedNodes[col, floor, row] = (colliders.Length > 0); if (drawGridNodeGizmos) { DrawGridNodeGizmos(col, floor, row, pos, size); } if (drawConnectionGizmos) { DrawConnectionGizmos(col, floor, row); } } } } } }
public override void Use(Vector3Int?pos = null) { base.Use(pos); if (!hasEgg) { ++countDown; } }
public static bool CheckIfNeighbourIsRoadInDictionary(Vector3Int?neighbourPosition, Dictionary <Vector3Int, GameObject> structuresToBeModified) { if (structuresToBeModified == null) { return(false); } return(structuresToBeModified.ContainsKey(neighbourPosition.Value)); }
public override void Use(Vector3Int?pos = null) { base.Use(pos); if (state != State.HOLE) { ++countDown; } }
private bool moveSafe(Vector3Int?move) { if (!move.HasValue) { return(true); } return(!notSafeMoves.Contains(move.Value)); }
public static void WriteVector3IntNullable(this NetworkWriter writer, Vector3Int?value) { writer.WriteBool(value.HasValue); if (value.HasValue) { writer.WriteVector3Int(value.Value); } }