/// <summary> /// The method which does all the complicated battle simulation. From calculating Damage to dealing Damage and so forth. /// Gets called when the event OnAnimFight is fired. When the needsAnimating property is false it will execute this code. /// </summary> /// <param Name="Attacker"></param> /// <param Name="Defender"></param> private void BattleSimulation(OnAnimFight evt) { if (evt.attacker != null && evt.defender != null && !evt.needsAnimating) { UnitGameObject attacker = evt.attacker; UnitGameObject defender = evt.defender; attacker.UnitGame.UpdateUnitColor(); Unit attUnit = attacker.UnitGame; Unit defUnit = defender.UnitGame; float damageToDefender = attUnit.Damage * attUnit.GetStrength() * attUnit.GetGroundModifier() * attUnit.GetUnitModifier(defender.type); float damageToAttacker = defUnit.Damage * defUnit.GetStrength() * defUnit.GetGroundModifier() * defUnit.GetUnitModifier(attacker.type); damageToDefender = Mathf.Clamp(damageToDefender, 1f, float.MaxValue); damageToAttacker = Mathf.Clamp(damageToAttacker, 1f, float.MaxValue); defUnit.DecreaseHealth(damageToDefender); if (defUnit.AttackRange >= attUnit.AttackRange) { attUnit.DecreaseHealth(damageToAttacker); } CheckUnitsHealth(attacker, defender); } }
// Use this for initialization void Start() { switch (name) { case "NorthEast": direction = 1; break; case "East": direction = 3; break; case "SouthEast": direction = 5; break; case "SouthWest": direction = 4; break; case "West": direction = 2; break; case "NorthWest": direction = 0; break; } unitGameObject = GetComponentInParent <UnitGameObject>(); }
public static Unit CreateUnit(UnitGameObject unit, bool isHero, UnitTypes type) { string unitType = isHero ? type + "Hero" : type.ToString(); string jsonString = Resources.Load <TextAsset>("JSON/Units/" + unitType).text; JSONNode jsonUnit = JSON.Parse(jsonString); int attackRange = jsonUnit["attackRange"].AsInt; int moveRange = jsonUnit["moveRange"].AsInt; bool canAttackAfterMove = jsonUnit["canAttackAfterMove"].AsBool; float maxHealth = jsonUnit["maxHealth"].AsFloat; float damage = jsonUnit["damage"].AsFloat; int cost = jsonUnit["cost"].AsInt; int fowLos = jsonUnit["fowLos"].AsInt; float baseLoot = jsonUnit["baseLoot"].AsFloat; JSONArray a = jsonUnit["unitModifiers"].AsArray; var modifiers = new Dictionary <UnitTypes, float>(); foreach (UnitTypes suit in (UnitTypes[])Enum.GetValues(typeof(UnitTypes))) { foreach (JSONNode item in a) { if (!String.IsNullOrEmpty(item[suit.ToString()]) && item[suit.ToString()] != suit.ToString()) { modifiers.Add(suit, item[suit.ToString()].AsFloat); } } } return(new Unit(unit, isHero, attackRange, moveRange, canAttackAfterMove, maxHealth, damage, cost, fowLos, baseLoot, modifiers)); }
private void Update() { if (CanClick && Input.GetMouseButtonDown(0) && ParentProduction.IsProductionOverlayActive && !ParentProduction.BuildingClickedProduction.Tile.HasUnit()) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit touchBox; if (Physics.Raycast(ray, out touchBox)) { if (touchBox.collider == this.collider) { BuildingGameObject buildingToProduceFrom = ParentProduction.BuildingClickedProduction; // Kind of ugly yet could not find better solution. The unit is created before we check if it can be bought. // Set it inactive immediatly and then check for enough Gold. If not then destroy else decrease the Gold and set it active. UnitGameObject unit = CreatorFactoryUnit.CreateUnit(buildingToProduceFrom.Tile, buildingToProduceFrom.index, type); unit.gameObject.SetActive(false); if (lm.CurrentLevel.CurrentPlayer.CanBuy(unit.UnitGame.Cost)) { unit.gameObject.SetActive(true); lm.CurrentLevel.CurrentPlayer.DecreaseGoldBy(unit.UnitGame.Cost); CanClick = false; ParentProduction.InitiateMoving(true); } else { Notificator.Notify("Not enough gold!", 1.5f); unit.DestroyUnit(); } } } } }
/// <summary> /// Show the attack highlights for the specified unit with the specified range. /// </summary> /// <param Name="unit"></param> /// <param Name="range"></param> /// <returns></returns> public int ShowAttackHighlights(UnitGameObject unit, int range) { foreach (var item in TileHelper.GetAllTilesWithinRange(unit.Tile.Coordinate, range)) { foreach (var tile in item.Value.Where(tile => tile.Value.HasUnit() && tile.Value.unitGameObject.index != unit.index)) { // If unit is an archer we don't need to calculate paths because archer can shoot over units, water etc. if (!unit.UnitGame.CanAttackAfterMove && !tile.Value.IsFogShown) { tile.Value.Highlight.ChangeHighlight(HighlightTypes.highlight_attack); highlight.HighlightObjects.Add(tile.Value.Highlight); } else { List <Node> path = movement.CalculateShortestPath(unit.Tile, tile.Value, true); if (path != null && path.Count <= unit.UnitGame.GetAttackMoveRange && !tile.Value.IsFogShown) { tile.Value.Highlight.ChangeHighlight(HighlightTypes.highlight_attack); highlight.HighlightObjects.Add(tile.Value.Highlight); } } } } int count = highlight.HighlightObjects.Count; highlight.IsHighlightOn = count > 0; return(count); }
/// <summary> /// Moves unit logically by calling on unitmove and graphically by calling on beginwalking /// </summary> /// <param name="goal">Destination</param> public void moveUnit(Point goal) { if (!finishedWalking && !isWalking && !attacking) { UnitGameObject activeUnit = initative[whoseTurn]; path = battleField.unitMove(activeUnit.LogicalPos, goal); BeginWalking(); } }
public void Moving(UnitGameObject unitMoving) { unitMoving.transform.position = Vector2.Lerp(unitMoving.Tile.Vector2, nodeList.Last().Tile.Vector2, GetTimePassed()); if (GetTimePassed() >= 1f) { // Show fow for the unit. dayStateControl.ShowFowWithinLineOfSight(unitMoving.index); // Remove the references from the old Tile. unitMoving.Tile.unitGameObject = null; unitMoving.Tile = null; // Remove the last Tile from the list. Tile newPosition = nodeList.Last().Tile; nodeList.Remove(nodeList.Last()); // Assign the references using the new Tile. newPosition.unitGameObject = unitMoving; unitMoving.Tile = newPosition; unitMoving.Tile.Vector2 = newPosition.Vector2; // Set the parent and position of the unit to the new Tile. unitMoving.transform.parent = newPosition.transform; unitMoving.transform.position = newPosition.transform.position; // Hide the fow for the unit. It will use the new Tile location. dayStateControl.HideFowWithinLineOfSight(unitMoving.index); StartTimeMoving = Time.time; } if (nodeList.Count <= 0) { highlight.ClearHighlights(); Tile endDestinationTile = unitMoving.Tile; if (endDestinationTile.HasLoot()) { endDestinationTile.Loot.PickUpLoot(levelManager.CurrentLevel.CurrentPlayer); } if (endDestinationTile.HasBuilding()) { CaptureBuildings capBuilding = GameObject.Find("_Scripts").GetComponent <CaptureBuildings>(); capBuilding.AddBuildingToCaptureList( endDestinationTile.buildingGameObject.BuildingGame); } if (unitMoving.UnitGame.CanAttackAfterMove && attack.ShowAttackHighlights(unitMoving, unitMoving.UnitGame.AttackRange) > 0) { unitMoving.UnitGame.HasMoved = true; } else { unitMoving.UnitGame.HasMoved = true; unitMoving.UnitGame.HasAttacked = true; } NeedsMoving = false; unitMoving.UnitGame.UpdateUnitColor(); } }
private static UnitGameObject ConfigUnitAndTile(Tile tile, GameObject obj) { UnitGameObject unit = ((GameObject)GameObject.Instantiate(obj)).GetComponent <UnitGameObject>(); tile.unitGameObject = unit; unit.transform.position = tile.transform.position; unit.transform.parent = tile.transform; unit.Tile = tile; return(unit); }
/// <summary> /// When a unit captured an trainingzone, train him to his hero form. /// </summary> /// <param Name="unitToHero">The unit to train to an hero.</param> private void OnTrainingzoneCapturedHero(UnitGameObject unitToHero) { if (!unitToHero.isHero) { Tile tiletoSpawn = unitToHero.Tile; PlayerIndex index = unitToHero.index; UnitTypes type = unitToHero.type; unitToHero.DestroyUnit(); CreatorFactoryUnit.CreateHeroUnit(tiletoSpawn, index, type); } }
public void FacingDirectionMovement(UnitGameObject moveUnit, Tile destination) { Vector3 direction = moveUnit.transform.position - destination.transform.position; var quaternion = new Quaternion(0, (direction.x > 0 ? 180 : 0), 0, 0); moveUnit.transform.rotation = quaternion; var attackerHealthQ = new Quaternion(0, 0, 0, (moveUnit.transform.position.y > 0 ? 0 : 180)); moveUnit.UnitHealthText.transform.rotation = attackerHealthQ; }
/// <summary> /// Call this method whenever a unit has moved onto an enemy or neutral building. /// </summary> /// <param Name="building"></param> public void AddBuildingToCaptureList(Building building) { UnitGameObject unitOnBuilding = building.BuildingGameObject.Tile.unitGameObject; if (!BuildingsBeingCaptured.Contains(building) && unitOnBuilding.index != building.BuildingGameObject.index) { BuildingsBeingCaptured.Add(building); } else if (BuildingsBeingCaptured.Contains(building) && unitOnBuilding.index == building.BuildingGameObject.index) { building.ResetCurrentCapturePoints(); BuildingsBeingCaptured.Remove(building); } }
/// <summary> /// Get called whenever an OnHighlightClick is fired. If it is possible it will attack an enemy unit. /// </summary> /// <param Name="evt"></param> public void BattlePreparation(OnHighlightClick evt) { if (evt.highlight != null) { HighlightObject highlightObj = evt.highlight; if (highlight.IsHighlightOn && !movement.NeedsMoving && highlightObj.highlightTypeActive == HighlightTypes.highlight_attack) { UnitGameObject attackingUnit = highlight.UnitSelected; UnitGameObject defendingUnit = highlightObj.Tile.unitGameObject; if (!attackingUnit.UnitGame.HasAttacked) { if (!attackingUnit.UnitGame.HasMoved || (attackingUnit.UnitGame.HasMoved && attackingUnit.UnitGame.CanAttackAfterMove)) { if (TileHelper.IsTileWithinRange(attackingUnit.transform.position, defendingUnit.transform.position, attackingUnit.UnitGame.AttackRange)) { attackingUnit.UnitGame.HasAttacked = true; attackingUnit.UnitGame.HasMoved = true; attackingUnit.UnitGame.PlaySound(UnitSoundType.Attack); highlight.ClearHighlights(); // Check if units are faces the wrong way FacingDirectionUnits(attackingUnit, defendingUnit); // Dispatch the animation fight event. But set the needsanimating to true. OnAnimFight fight = new OnAnimFight(); fight.attacker = attackingUnit; fight.defender = defendingUnit; fight.needsAnimating = true; EventHandler.dispatch(fight); } else { Notificator.Notify("Move to this unit to attack!", 1f); } } } } } }
private void CheckUnitsHealth(UnitGameObject attacker, UnitGameObject defender) { if (!attacker.UnitGame.IsAlive() && !defender.UnitGame.IsAlive()) { defender.UnitGame.OnDeath(); attacker.UnitGame.OnDeath(); } else if (!attacker.UnitGame.IsAlive()) { attacker.UnitGame.OnDeath(); defender.UnitGame.AddLoot(10); } else if (!defender.UnitGame.IsAlive()) { defender.UnitGame.OnDeath(); attacker.UnitGame.AddLoot(10); } }
private void FacingDirectionUnits(UnitGameObject attacker, UnitGameObject defender) { Vector3 attDirection = defender.transform.position - attacker.transform.position; Vector3 defDirection = attacker.transform.position - defender.transform.position; var attackerQ = new Quaternion(0, (attDirection.x >= 0 ? 0 : 180), 0, 0); var defenderQ = new Quaternion(0, (defDirection.x >= 0 ? 0 : 180), 0, 0); attacker.transform.rotation = attackerQ; defender.transform.rotation = defenderQ; var attackerHealthQ = new Quaternion(0, 0, 0, (attacker.transform.position.y > 0 ? 0 : 180)); var defenderHealthQ = new Quaternion(0, 0, 0, (defender.transform.position.y > 0 ? 0 : 180)); attacker.UnitHealthText.transform.rotation = attackerHealthQ; defender.UnitHealthText.transform.rotation = defenderHealthQ; // While attacking don't show the UnitHealth attacker.UnitHealthText.renderer.enabled = false; defender.UnitHealthText.renderer.enabled = false; }
/// <summary> /// Method finds wich enemy unit to attack and then calls the checkPos method /// </summary> /// <param name="activeUnit">The unit whose turn it is</param> public void act(UnitGameObject activeUnit) { x = activeUnit.LogicalPos.x; y = activeUnit.LogicalPos.y; UnitGameObject[] possibleTargets = new UnitGameObject[UnitTree.TREESIZE + 1]; int next = 0; //Finds enemy units for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (field[i, j].GetComponent <GroundGameObject>().IsOccupied&& unitsOnField[i, j] != null && unitsOnField[i, j].GetComponent <UnitGameObject>().AttackingSide) { possibleTargets[next++] = unitsOnField[i, j].GetComponent <UnitGameObject>(); } } } //Finds closest enemy unit UnitGameObject target = possibleTargets[0]; int distance = HandyMethods.DistanceHex(activeUnit.LogicalPos, target.LogicalPos); for (int i = 1; i < possibleTargets.Length; i++) { if (possibleTargets[i] == null) { break; } int tmpDistance = HandyMethods.DistanceHex(activeUnit.LogicalPos, possibleTargets[i].LogicalPos); if (tmpDistance < distance) { target = possibleTargets[i]; distance = tmpDistance; } } checkPos(target.LogicalPos.x, target.LogicalPos.y); }
public Settler(int id, UnitAsset unitAsset, Hex hex, Player player) { this.Id = id; this.UnitInfo = unitAsset; this.PrivateName = unitAsset.Name; this.Player = player; this.Hex = hex; this.CurrentHealth = unitAsset.MaxHealth; hex.Unit = this; this.PrivateName = "Settler"; UnitGameObject = GameObject.Instantiate(unitAsset.UnitPrefab); UnitGameObject.transform.position += hex.Position(); UnitComponent = UnitGameObject.AddComponent <UnitComponent>(); UnitComponent.UnitLogic = this; foreach (Collider c in UnitGameObject.GetComponents <Collider>()) { c.enabled = false; } foreach (Collider c in UnitGameObject.GetComponents <Collider>()) { c.enabled = false; } }
/// <summary> /// Updates unit amount text representation /// </summary> /// <param name="ugo">Unit to be updated</param> public void updateAmount(UnitGameObject ugo) { ugo.GetComponentInChildren <TextMesh>().text = "" + ugo.UnitTree.getUnitAmount(ugo.PosInUnitTree); }
/// <summary> /// Readies initative and populates 2d array for units /// </summary> /// <param name="attacker">Attacking hero</param> /// <param name="defender">Defending units</param> public void populateInitative(Hero attacker, UnitTree defender) { unitsOnField = new GameObject[width, height]; Initative = new UnitGameObject[UnitTree.TREESIZE * 2]; int logPos = 0; int increment = Height / UnitTree.TREESIZE; int place = 0; livingAttackers = livingDefenders = 0; // Adds attacking units UnitTree units = attacker.Units; for (int i = 0; i < UnitTree.TREESIZE; i++) { if (units.GetUnits()[i] != null) { GameObject go = Instantiate(unit, parent.transform); go.name = "a" + i; SpriteRenderer sr = go.GetComponent <SpriteRenderer>(); sr.sprite = troll; sr.sortingLayerName = "CombatUnits"; TextMesh tm = go.GetComponentInChildren <TextMesh>(); tm.text = "" + units.getUnitAmount(i); tm.GetComponent <Renderer>().sortingLayerName = "CombatUnits"; UnitGameObject ugo = go.GetComponent <UnitGameObject>(); ugo.UnitTree = units; ugo.PosInUnitTree = i; ugo.GraphicalBattlefield = this; ugo.AttackingSide = true; ugo.Initative = units.GetUnits()[i].Unitstats.Initative; ugo.LogicalPos = new Point(0, place); Initative[logPos++] = ugo; //set correct graphical pos go.transform.localPosition = field[0, place].transform.localPosition; UnitsOnField[0, place] = go; field[0, place].GetComponent <GroundGameObject>().IsOccupied = true; livingAttackers++; } place += increment; } //Adds defending units units = defender; place = 0; for (int i = 0; i < UnitTree.TREESIZE; i++) { if (units.GetUnits()[i] != null) { GameObject go = Instantiate(unit, parent.transform); go.name = "d" + i; SpriteRenderer sr = go.GetComponent <SpriteRenderer>(); sr.flipX = true; sr.sprite = troll; sr.sortingLayerName = "CombatUnits"; TextMesh tm = go.GetComponentInChildren <TextMesh>(); tm.text = "" + units.getUnitAmount(i); tm.GetComponent <Renderer>().sortingLayerName = "CombatUnits"; UnitGameObject ugo = go.GetComponent <UnitGameObject>(); ugo.UnitTree = units; ugo.PosInUnitTree = i; ugo.GraphicalBattlefield = this; ugo.AttackingSide = false; ugo.Initative = units.GetUnits()[i].Unitstats.Initative; ugo.LogicalPos = new Point(width - 1, place); Initative[logPos++] = ugo; //set correct graphical pos go.transform.localPosition = field[width - 1, place].transform.localPosition; UnitsOnField[Width - 1, place] = go; field[width - 1, place].GetComponent <GroundGameObject>().IsOccupied = true; livingDefenders++; } place += increment; } Array.Sort(initative); Array.Reverse(initative); WhoseTurn = 0; initative[whoseTurn].ItsTurn = true; }
/// <summary> /// Initiates attack on unit /// </summary> /// <param name="defender">Unit thats being attacked</param> /// <param name="goal">Place on field attacking unit is going to</param> public void attackUnit(UnitGameObject defender, Point goal) { if (!isWalking && !finishedWalking && !attacking) { UnitGameObject activeUnit = initative[whoseTurn]; Unit attackingUnit = activeUnit.UnitTree.GetUnits()[activeUnit.PosInUnitTree]; //If unit does not need to move, call on method for attacking without moving if (activeUnit.LogicalPos.Equals(goal)) { battleField.attackWithoutMoving(activeUnit.LogicalPos, defender.LogicalPos, false); beginAttacking(defender.LogicalPos.x); } else { //checks if unit is ranged, and if it has ammo. if not move and attack if (attackingUnit.IsRanged) { Ranged r = (Ranged)attackingUnit; if (r.Ammo > 0 && !r.Threatened) { battleField.attackWithoutMoving(activeUnit.LogicalPos, defender.LogicalPos, true); beginAttacking(defender.LogicalPos.x); } else { path = battleField.UnitMoveAndAttack(activeUnit.LogicalPos, goal, defender.LogicalPos); BeginWalking(); attacking = true; } } else { path = battleField.UnitMoveAndAttack(activeUnit.LogicalPos, goal, defender.LogicalPos); BeginWalking(); attacking = true; } } //Updates living units counts if (defender.UnitTree.getUnitAmount(defender.PosInUnitTree) == 0) { if (defender.AttackingSide) { livingAttackers--; } else { livingDefenders--; } } if (activeUnit.UnitTree.getUnitAmount(activeUnit.PosInUnitTree) == 0) { if (activeUnit.AttackingSide) { livingAttackers--; } else { livingDefenders--; } } Debug.Log(livingAttackers + " " + livingDefenders); updateAmount(defender); updateAmount(getUnitWhoseTurnItIs()); } }
public OnUnitClick(UnitGameObject _unit) { unit = _unit; }
public OnAnimFight(UnitGameObject _attacker, UnitGameObject _defender, bool _needsAnimating) { attacker = _attacker; defender = _defender; needsAnimating = _needsAnimating; }
/// <summary> /// This method is called by the GameManager within the NextPlayer method. It will calculate all of the capturing stuff. /// </summary> public void CalculateCapturing() { int count = BuildingsBeingCaptured.Count; for (int i = 0; i < count; i++) { Building building = BuildingsBeingCaptured[i]; if (building.BuildingGameObject.Tile.HasUnit()) { UnitGameObject unitOnBuilding = building.BuildingGameObject.Tile.unitGameObject; float health = unitOnBuilding.UnitGame.CurrentHealth; building.IncreaseCapturePointsBy(health); unitOnBuilding.UnitGame.DecreaseHealth(building.DamageToCapturingUnit); if (!unitOnBuilding.UnitGame.IsAlive()) { unitOnBuilding.UnitGame.OnDeath(); } if (building.HasCaptured()) { if (building.BuildingGameObject.type != BuildingTypes.Headquarters) { BuildingTypes type = building.BuildingGameObject.type; BuildingsBeingCaptured.Remove(building); count--; i--; building.BuildingGameObject.DestroyBuilding(); CreatorFactoryBuilding.CreateBuilding(unitOnBuilding.Tile, unitOnBuilding.index, type); if (type == BuildingTypes.TrainingZone) { OnTrainingzoneCapturedHero(unitOnBuilding); } } else { LevelManager lm = GameObjectReferences.GetGlobalScriptsGameObject().GetComponent <LevelManager>(); Camera.main.backgroundColor = lm.CurrentLevel.Players[unitOnBuilding.index].PlayerColor; GameObject.FindGameObjectWithTag("Level").SetActive(false); GameObject.Find("_Scripts").GetComponent <GameBar>().enabled = false; GameObject.Find("_Scripts").GetComponent <Notificator>().enabled = false; GameObject.Find("NotificationText").GetComponent <TextMesh>().text = unitOnBuilding.index + " has won the game! \n\nPress anywhere to return to the menu."; lm.CurrentLevel.IsEnded = true; } } } else { building.DecreaseCapturePointsBy(building.CapturePointsDecreasedBy); if (building.CurrentCapturePoints <= 0f) { BuildingsBeingCaptured.Remove(building); count--; i--; } } } }
// Update is called once per frame void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, Mathf.Infinity, MouseLayerMask)) { currentMousePoint = hit.point; #region Visszavonások if (GUISetup.GhostActive) { return; } #endregion //Store point at mouse button down if (Input.GetMouseButtonDown(0)) { if (EventSystem.current.IsPointerOverGameObject()) { EndModes(); } mouseDownPoint = hit.point; TimeLeftBeforeDeclareDrag = TimeLimitBeforeDeclareDrag; MouseDragStart = Input.mousePosition; StartedDrag = true; #region CommandRegion if (MoveMode) { for (int i = 0; i < CurrentlySelectedUnits.Count; i++) { AIDestinationSetter setter = (CurrentlySelectedUnits[i] as GameObject).GetComponent <AIDestinationSetter>(); if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Unit")) { setter.target = hit.collider.gameObject.transform; } else { setter.ai.destination = mouseDownPoint; } setter.ai.isStopped = false; } MoveMode = false; } if (AttackMode) { for (int i = 0; i < CurrentlySelectedUnits.Count; i++) { AIDestinationSetter setter = (CurrentlySelectedUnits[i] as GameObject).GetComponent <AIDestinationSetter>(); if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Unit")) { setter.target = hit.collider.gameObject.transform; } else { setter.ai.destination = mouseDownPoint; (CurrentlySelectedUnits[i] as GameObject).GetComponent <Unit>().aMove = true; } setter.ai.isStopped = false; } AttackMode = false; } if (RepairMode) { for (int i = 0; i < CurrentlySelectedUnits.Count; i++) { AIDestinationSetter setter = (CurrentlySelectedUnits[i] as GameObject).GetComponent <AIDestinationSetter>(); Unit unit = (CurrentlySelectedUnits[i] as GameObject).GetComponent <Unit>(); if (unit.isGatherer && hit.collider.gameObject.layer == LayerMask.NameToLayer("Unit") && !Game.players.Where(x => x.empireName.Equals(unit.Owner)).SingleOrDefault().enemies.Contains(Game.players.Where(x => x.empireName.Equals(hit.collider.transform.GetComponent <Unit>().Owner)).SingleOrDefault())) { setter.target = hit.collider.gameObject.transform; setter.ai.isStopped = false; } } RepairMode = false; } #endregion } else if (Input.GetMouseButton(0)) { //If the user is not dragging, lets do the tests if (!UserIsDragging) { TimeLeftBeforeDeclareDrag = Time.deltaTime; if (TimeLeftBeforeDeclareDrag <= 0f || UserDraggingByPosition(MouseDragStart, Input.mousePosition)) { UserIsDragging = true; } } } else if (Input.GetMouseButtonUp(0)) { //User is dragging if (UserIsDragging) { FinishedDragOnThisFrame = true; } UserIsDragging = false; } //Mouse click if (!UserIsDragging) { //Debug.Log(hit.collider.name); #region Jobb klikk if (Input.GetMouseButtonDown(1) && !EventSystem.current.IsPointerOverGameObject()) { if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Unit")) { SelectTargets(hit); } else if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Resources")) { SelectGatherTargets(hit); } else if (hit.collider.name == "TerrainMain") { SelectRally(hit); RightClickPoint = hit.point; DeselectTargets(); } } #endregion // End of Terrain else { //Hitting other objects if (Input.GetMouseButtonUp(0) && DidUserClickLeftMouse(mouseDownPoint) && !EventSystem.current.IsPointerOverGameObject()) { //Is the user hitting a unit? if ((hit.collider.gameObject.GetComponent <Unit>() || hit.collider.gameObject.layer == LayerMask.NameToLayer("SelectMesh")) && hit.collider.transform.parent.parent.name == game.currentSolarSystem.Name) { Transform UnitGameObject; if (hit.collider.gameObject.layer == LayerMask.NameToLayer("SelectMesh")) { UnitGameObject = hit.collider.transform.parent.transform; } else { UnitGameObject = hit.collider.transform; } //Are we selecting a different object? if (!UnitAlreadyInCurrentySelectedUnits(UnitGameObject.gameObject)) { //If shift key is not down, remove the rest of the units if (!Common.ShiftKeysDown()) { DeselectGameObjectsIfSelected(); } GameObject SelectedObj = UnitGameObject.Find("Selected").gameObject; if (UnitGameObject.GetComponent <Unit>().Owner != Game.currentPlayer.empireName) { DeselectGameObjectsIfSelected(); SelectedObj.GetComponent <Projector>().material.color = Color.red; } else { SelectedObj.GetComponent <Projector>().material.color = Color.green; } SelectedObj.SetActive(true); //Add unit to currently selected units CurrentlySelectedUnits.Add(UnitGameObject.gameObject); //Change the unit selected value to true UnitGameObject.gameObject.GetComponent <Unit>().Selected = true; } else { //Unit is currently in the selected units arraylist //Remove the units if (Common.ShiftKeysDown()) { RemoveUnitFromCurrentlySelectedUnits(UnitGameObject.gameObject); } else if (!Common.ShiftKeysDown()) { DeselectGameObjectsIfSelected(); GameObject SelectedObj = UnitGameObject.Find("Selected").gameObject; if (UnitGameObject.GetComponent <Unit>().Owner != Game.currentPlayer.empireName) { SelectedObj.GetComponent <Projector>().material.color = Color.red; } else { SelectedObj.GetComponent <Projector>().material.color = Color.green; } SelectedObj.SetActive(true); UnitGameObject.gameObject.GetComponent <Unit>().Selected = true; //Add unit to currently selected units CurrentlySelectedUnits.Add(UnitGameObject.gameObject); } } } else { //If this object is not a unit if (!Common.ShiftKeysDown() && !EventSystem.current.IsPointerOverGameObject()) { DeselectGameObjectsIfSelected(); } } } } } else { if (Input.GetMouseButtonUp(0) && DidUserClickLeftMouse(mouseDownPoint) && !EventSystem.current.IsPointerOverGameObject()) { if (!Common.ShiftKeysDown()) { DeselectGameObjectsIfSelected(); } } } //End of dragging } //End of raycasthit if (CurrentlySelectedUnits.Count != 0) { CurrentlyFocusedUnit = CurrentlySelectedUnits[0] as GameObject; } else { CurrentlyFocusedUnit = null; } if (!Common.ShiftKeysDown() && StartedDrag && UserIsDragging) { DeselectGameObjectsIfSelected(); StartedDrag = false; } #region Csoport létrehozás if (CurrentlySelectedUnits.Count != 0 && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))) { for (int i = 1; i < 10; i++) { if (Input.GetKey(keyCodes[i - 1])) { Grouping[i] = new ArrayList(); for (int j = 0; j < CurrentlySelectedUnits.Count; j++) { if ((CurrentlySelectedUnits[j] as GameObject).GetComponent <Unit>().Owner == Game.currentPlayer.empireName) { Grouping[i].Add(CurrentlySelectedUnits[j]); } } Debug.Log(Grouping[i].Count); } } } #endregion #region Csoport kiválasztás if (GetAnyKey(keyCodes)) { for (int i = 1; i < 10; i++) { if (Input.GetKey(keyCodes[i - 1]) && Grouping[i] != null) { DeselectGameObjectsIfSelected(); for (int j = 0; j < Grouping[i].Count; j++) { CurrentlySelectedUnits.Add((Grouping[i])[j]); } } } Debug.Log(CurrentlySelectedUnits.Count); for (int j = 0; j < CurrentlySelectedUnits.Count; j++) { GameObject SelectedObj = CurrentlySelectedUnits[j] as GameObject; SelectedObj.GetComponent <Unit>().Selected = true; SelectedObj.transform.Find("Selected").gameObject.SetActive(true); Debug.Log(j + ". aktív"); } } #endregion Debug.DrawRay(ray.origin, ray.direction * 1000, Color.yellow); #region Dragbox variables if (UserIsDragging && currentMousePoint != Vector3.positiveInfinity) { BoxWidth = Camera.main.WorldToScreenPoint(mouseDownPoint).x - Camera.main.WorldToScreenPoint(currentMousePoint).x; BoxHeight = Camera.main.WorldToScreenPoint(mouseDownPoint).y - Camera.main.WorldToScreenPoint(currentMousePoint).y; BoxLeft = Input.mousePosition.x; BoxTop = (Screen.height - Input.mousePosition.y) - BoxHeight; if (Common.FloatToBool(BoxWidth)) { if (Common.FloatToBool(BoxHeight)) { BoxStart = new Vector2(Input.mousePosition.x, Input.mousePosition.y + BoxHeight); } else { BoxStart = new Vector2(Input.mousePosition.x, Input.mousePosition.y); } } else if (!Common.FloatToBool(BoxWidth)) { if (Common.FloatToBool(BoxHeight)) { BoxStart = new Vector2(Input.mousePosition.x + BoxWidth, Input.mousePosition.y + BoxHeight); } else { BoxStart = new Vector2(Input.mousePosition.x + BoxWidth, Input.mousePosition.y); } } BoxFinish = new Vector2(BoxStart.x + Mathf.Abs(BoxWidth), BoxStart.y - Mathf.Abs(BoxHeight)); } #endregion }
/// <summary> /// Checks in a growing circular fashion what you can reach and flips the appropriate bool /// </summary> /// <param name="startingPoint">Position of unit</param> /// <param name="speed">How many steps the unit can take</param> public void flipReachable(Point startingPoint, int speed) { // List for all nodes that are to be evaluvated List <Node> openSet = new List <Node>(); UnitGameObject aktiveUnit = units[startingPoint.x, startingPoint.y].GetComponent <UnitGameObject>(); Unit u = aktiveUnit.UnitTree.GetUnits()[aktiveUnit.PosInUnitTree]; Ranged r = null; if (u.IsRanged) { r = (Ranged)u; r.Threatened = false; } //Adds starting node to openSet Node s = field[startingPoint.x, startingPoint.y]; s.WalkedSteps = 0; s.InOpenSet = true; openSet.Add(s); //Loops as long as there are unevaluvated nodes while (openSet.Count > 0) { //Fetches current node from openset Node cur = openSet[0]; //Removes cur from openset and marks as evaluvated openSet.Remove(cur); cur.InOpenSet = false; cur.Evaluvated = true; //Flips bool for reachable or attackable if unit can reach cur if (cur.Ggo.IsOccupied && units[cur.Pos.x, cur.Pos.y] != null && cur.WalkedSteps <= speed + 1 && aktiveUnit.AttackingSide != units[cur.Pos.x, cur.Pos.y].GetComponent <UnitGameObject>().AttackingSide) { units[cur.Pos.x, cur.Pos.y].GetComponent <UnitGameObject>().Attackable = true; if (u.IsRanged && cur.WalkedSteps == 1) { r.Threatened = true; } cur.Ggo.MarkReachable(ATTACKABLE); } else if (cur.WalkedSteps <= speed) { cur.Ggo.Reachable = true; cur.Ggo.MarkReachable(!ATTACKABLE); } if (cur.Ggo.IsOccupied && !cur.Pos.Equals(startingPoint)) { continue; } //Finds walkable neighbours Node[] neighbours = findNeighboursHex(cur.Pos); //Loops trou neighbours for (int i = 0; i < neighbours.Length && neighbours[i] != null; i++) { Node neighbour = neighbours[i]; // If already evaluvated, skip node if (neighbour.Evaluvated) { continue; } // If not in openSet, add to openSet and calculate WalkedSteps if (!neighbour.InOpenSet) { neighbour.WalkedSteps = cur.WalkedSteps + 1; neighbour.InOpenSet = true; //Inserts neighbour node into openset at sorted position int index = Math.Abs(openSet.BinarySearch(neighbour)); if (index >= openSet.Count) { openSet.Add(neighbour); } else { openSet.Insert(index, neighbour); } } // OpenSet contains node, then check if current path is better. else { int newWalkedSteps = cur.WalkedSteps + 1; if (neighbour.WalkedSteps > newWalkedSteps) { neighbour.WalkedSteps = newWalkedSteps; } } } //Breaks loop if next node to be checked is unreachable if (cur.WalkedSteps == speed + 2) { break; } } //Readies for new run for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { field[x, y].Evaluvated = false; field[x, y].InOpenSet = false; } } }