public void Merge(ActorBehavior behaviour) { Vector3 rootRotation = new Vector3(rotation); Vector3 rootTranslation = new Vector3(translation); DualQuaternion rootTransform = DualQuaternion.FromRotationTranslation( behaviour.model.MainDefinition.BoneSystem.RootBone.RotationOrder.FromEulerAngles(MathExtensions.DegreesToRadians(rootRotation)), rootTranslation); behaviour.dragHandle.Transform = rootTransform.ToMatrix(); var poseDeltas = behaviour.ikAnimator.PoseDeltas; poseDeltas.ClearToZero(); foreach (var bone in behaviour.model.MainDefinition.BoneSystem.Bones) { Vector3 angles; if (boneRotations.TryGetValue(bone.Name, out var values)) { angles = new Vector3(values); } else { angles = Vector3.Zero; } var twistSwing = bone.RotationOrder.FromTwistSwingAngles(MathExtensions.DegreesToRadians(angles)); poseDeltas.Rotations[bone.Index] = twistSwing; } }
static void RegisterBehaviors(Type[] actors) { foreach (var each in actors) { ActorBehavior.Register(each); } }
void RegisterBehaviors() { foreach (var actor in assemblies.SelectMany(x => x.ActorTypes())) { ActorBehavior.Register(actor); } }
/// <summary> /// Initiates combat between this squad and the target. /// </summary> /// <param name="target">Target.</param> protected void beginCombatWithTarget(ActorBehavior target) { // Capture the combat camera. CombatSystemBehavior combatSystem = GameObject.Find("Combat Camera").GetComponent <CombatSystemBehavior>(); if (combatSystem == null) { Debug.LogError("Unable to find a valid combat system in scene!"); return; } // Capture the offensive and defensive combat squads CombatSquadBehavior offensiveSquad = actor.GetComponent <CombatSquadBehavior>(); if (!offensiveSquad) { Debug.LogError("Attempted to enter combat with an invalid offensive squad!"); return; } CombatSquadBehavior defensiveSquad = target.GetComponent <CombatSquadBehavior>(); if (!defensiveSquad) { Debug.LogError("Attempted to enter combat with an invalid defensive squad!"); return; } // Hide the target movement points. grid.HideMovePoints(); // Begin combat! combatSystem.BeginCombat(offensiveSquad, defensiveSquad, grid); }
private void ActBhvr_DidGetHit(ActorBehavior arg1, HitStats arg2) { // Reset stun counter Debug.Log(this.gameObject.name + "got Hit"); // Call Stun Function Here }
/// <summary> /// Initiates combat between this squad and the target. /// </summary> /// <param name="target">Target.</param> protected void beginCombatWithTarget(ActorBehavior target) { // Capture the combat camera. CombatSystemBehavior combatSystem = GameObject.Find ("Combat Camera").GetComponent<CombatSystemBehavior>(); if(combatSystem == null) { Debug.LogError ("Unable to find a valid combat system in scene!"); return; } // Capture the offensive and defensive combat squads CombatSquadBehavior offensiveSquad = actor.GetComponent<CombatSquadBehavior>(); if(!offensiveSquad) { Debug.LogError ("Attempted to enter combat with an invalid offensive squad!"); return; } CombatSquadBehavior defensiveSquad = target.GetComponent<CombatSquadBehavior>(); if(!defensiveSquad) { Debug.LogError ("Attempted to enter combat with an invalid defensive squad!"); return; } // Hide the target movement points. grid.HideMovePoints(); // Begin combat! combatSystem.BeginCombat (offensiveSquad, defensiveSquad, grid); }
void OnTriggerEnter2D(Collider2D coll) { bool contractedeach = false; if (coll.gameObject.tag == "Enemy" && gameObject.tag != "EBullet") { ActorBehavior collBehavior_E = coll.gameObject.GetComponent <ActorBehavior>(); collBehavior_E.Life -= status.damage * GameObject.FindGameObjectWithTag("Player").GetComponent <StatusMultiple>().MulDamage; contractedeach = true; } if (coll.gameObject.tag == "PlayerHittags" && gameObject.tag != "PBullet") { ActorBehavior collBehavior_P = coll.gameObject.transform.parent.gameObject.GetComponent <ActorBehavior>(); collBehavior_P.Life -= status.damage; contractedeach = true; } if ((!status.Penetrative && contractedeach == true) || (coll.gameObject.tag == "Terrain")) { transform.DetachChildren(); Destroy(this.gameObject); } }
// Use this for initialization void Start() { Actor = GetComponent <ActorBehavior>(); PVel = GetComponent <Rigidbody2D>(); Actorbehavior = GetComponent <ActorBehavior>(); Multi = GetComponent <StatusMultiple>(); SceneManager.activeSceneChanged += ActiveSceneLD; }
// Use this for initialization void Start() { Behavior = GetComponent <ActorBehavior>(); level = GameObject.Find("WorldSetting").GetComponent <Level>(); Behavior.MaxLife = Behavior.MaxLife * (1.0f + level.Currentlevel / 100); Behavior.Life = Behavior.MaxLife; Behavior.CurrentLife = Behavior.MaxLife; }
// Use this for initialization void Start() { Behavior = GetComponent <ActorBehavior>(); Player = GameObject.FindGameObjectWithTag("Player"); Rigid2d = GetComponent <Rigidbody2D>(); GameObject CurrentGuns = Instantiate(AttachedGun, transform) as GameObject; CurrentGuns.name = AttachedGun.name; }
// Use this for initialization void Start() { text = GetComponent <UnityEngine.UI.Text>(); actor = GameObject.FindGameObjectWithTag("Player").GetComponent <ActorBehavior>(); GaugeBase = GameObject.Find("EnergyGauge_1").GetComponent <UnityEngine.UI.Image>(); GaugeExtra = GameObject.Find("EnergyGauge_2").GetComponent <UnityEngine.UI.Image>(); }
public override void ComponentAwake() { player = GetRequiredObject(GameObjects.Actors.Player); rigidBody = GetRequiredComponent <Rigidbody2D>(); actorBehavior = GetRequiredComponent <ActorBehavior>(); explosionPrefab = GetRequiredResource <GameObject>($"{ResourcePaths.PrefabsFolder}/Explosions/EnemyExplosion"); base.ComponentAwake(); }
/// <summary> /// Simply delays until the combat sequence has finished, then moves to the Picking Squad state. /// </summary> public void UpdateState_WaitingForCombat() { if (GridBehavior.inCombat) { return; } selectedActor = null; State = AIState.PickingSquad; }
public override void ComponentAwake() { CreateTimers(); audioSource = GetRequiredComponent <AudioSource>(); rigidBody = GetRequiredComponent <Rigidbody2D>(); actorBehavior = GetRequiredComponent <ActorBehavior>(); externalVelocity = Vector2.zero; base.ComponentAwake(); }
public static void Mock(this ActorBehavior behavior) { behavior.mocked = true; var self = behavior.actor.Self as ActorRefMock; if (self == null) { throw new InvalidOperationException("Actor runtime should be a mock as well"); } }
//---------------| void Start() { actorBehavior = GetComponent<ActorBehavior>(); controller = GetComponent<CharacterController>(); camera = GameObject.Find ("Camera"); if (actorBehavior != null) { maxVel = actorBehavior.GetStat(ActorData.StatType.AGILITY); jump = actorBehavior.GetStat (ActorData.StatType.STRENGTH); actorBehavior.data.name = "Player"; } }
public override void ComponentAwake() { intervalTimer = GetRequiredComponent <IntervalTimerComponent>(); intervalTimer.OnIntervalReached.AddListener(ShootIntervalReached); actorBehavior = GetRequiredComponent <ActorBehavior>(); explosionObject = GetRequiredResource <GameObject>($"{ResourcePaths.PrefabsFolder}/Explosions/GruntExplosion"); bullet = GetRequiredResource <GameObject>($"{ResourcePaths.PrefabsFolder}/Projectiles/EnemyBullet"); base.ComponentAwake(); }
public override void Deactivate() { ActorBehavior b = _scene.GetGameObjectPool().GetActorBehavior(currentBehaviorID); if (b != null) { b.Alive = false; } IsActive = false; _scene.GetGameObjectPool().GetActor(OwnerID).RemoveBehavior(currentBehaviorID); StartCooldown(); }
public override void ComponentStart() { animator = GetRequiredComponent <Animator>(); healthImage = GetRequiredComponent <Image>(); GameObject player = GetRequiredObject(GameObjects.Actors.Player); actorBehavior = GetRequiredComponent <ActorBehavior>(player); presentedHealth = actorBehavior.Health; base.ComponentStart(); }
public override void Deactivate() { _scene.WriteMessage("Your bound spirit dissapates."); ActorBehavior b = _scene.GetGameObjectPool().GetActorBehavior(currentBehaviorID); if (b != null) { b.Alive = false; } IsActive = false; _scene.GetGameObjectPool().GetActor(OwnerID).RemoveBehavior(currentBehaviorID); StartCooldown(); }
private void ActBhvr_DidGetHit(ActorBehavior dfnsActBhvr, HitStats atckHitStats) { if (atckHitStats.WasBlocked) { // Flashes the mesh when hit blocked StartCoroutine(colorFlash(blckMeshColor)); } else { // Flashes the mesh when damaged StartCoroutine(colorFlash(dmgMeshColor)); } }
//---------// // Use this for initialization void Start() { animator = GetComponent <Animator>(); rigidplayer = GetComponent <Rigidbody2D>(); Actor = GetComponent <ActorBehavior>(); for (int i = 0; i < 10; i++) { anim_cont[i] = Resources.Load ("Enemy/" + Actor.Actorname + "/Animation/Overrider/D" + i) as RuntimeAnimatorController; } //---// }
public ActorBehavior GetActorBehavior(int key) { ActorBehavior b = null; GameObject obj = GetGameObject(key); if (obj != null && obj is ActorBehavior) { b = (ActorBehavior)obj; } return(b); }
public override void Deactivate() { _scene.WriteMessage("Your scales fall off."); ActorBehavior b = _scene.GetGameObjectPool().GetActorBehavior(BehaviorIDs[0]); if (b != null) { b.Alive = false; } IsActive = false; _scene.GetGameObjectPool().GetActor(OwnerID).RemoveBehavior(BehaviorIDs[0]); BehaviorIDs.Clear(); StartCooldown(); }
/// <summary> /// Waits for the left mouse button to be clicked, then performs a raycast to determine if the player has clicked /// on one of her own squads. /// </summary> /// <remarks> /// Transitions: /// Player Clicks Valid Squad -> SelectingMovement /// </remarks> private void updateSelectingUnit() { // Wait for the left mouse button to be pressed. if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Perform raycasting and store a list of all objects that have been selected. List <RaycastHit> hits = new List <RaycastHit>(); hits.AddRange(Physics.RaycastAll(ray)); // Iterate over the selection list to determine if the player has clicked on one of her squads. foreach (RaycastHit hitInfo in hits.OrderBy(l => l.distance)) { // Capture the actor behavior on the hit object. ActorBehavior actor = hitInfo.transform.GetComponent <ActorBehavior>(); if (actor == null) { continue; } // Ensure that the unit has not moved and belongs to the player. if (!actor.actorHasMovedThisTurn && actor.theSide == inputSide) { // Mark the actor as selected. selectedSquad = actor; startingPoint = actor.currentMovePoint; // Begin the scripted "Idle" animation. UnitIdleAnimationBehavior[] idles = selectedSquad.GetComponentsInChildren <UnitIdleAnimationBehavior>(); foreach (UnitIdleAnimationBehavior idle in idles) { idle.Active = true; } // Enable rendering of valid target movement nodes. if (actor.currentMovePoint != null) { actor.currentMovePoint.HighlightValidNodes(actor, grid); } // STATE CHANGE: SelectingUnit -> SelectingMovement controlState = GridControlState.SelectingMovement; break; } } } }
void PreviewBehaviorHurtBox(ActorBehavior behavior) { if (GUILayout.Button("Preview Hurtbox")) { if (behavior == null) { Debug.LogError("Behavior is Null"); return; } hurtBox.transform.localPosition = behavior.hurtBoxInfo.position; hurtBox.transform.localRotation = behavior.hurtBoxInfo.rotation; hurtBox.transform.localScale = behavior.hurtBoxInfo.scale; } }
public IEnumerator TakeAction() { if (_shouldBeDestroyed) { yield return(null); } this.behavior = GetComponent <ActorBehavior>(); _energy -= 1; behavior.TakeAction(); while (!behavior.IsDone) { yield return(null); } }
public override void Deactivate() { if (BehaviorIDs.Count > 0) { ActorBehavior b = _scene.GetGameObjectPool().GetActorBehavior(BehaviorIDs[0]); if (b != null) { b.Alive = false; } _scene.GetGameObjectPool().GetActor(OwnerID).RemoveBehavior(BehaviorIDs[0]); BehaviorIDs.Clear(); } IsActive = false; StartCooldown(); }
/// <summary> /// Updates the unit prefabs, in case some units have been destroyed since the last update cycle. /// </summary> public void Update() { if (unitCount != squad.Units.Count) { updateSquadVisuals(); } ActorBehavior actor = GetComponent <ActorBehavior>(); if (actor == null) { return; } selNode.renderer.material.color = (actor.actorHasMovedThisTurn ? Color.gray : baseColor); }
public void ShutdownBehavior(ActorBehavior behavior) { if (null != ModelSprite) { behavior.SpriteAnimationHelper.RemoveRenderer(ModelSprite); } if (null != SpineModel) { behavior.SpineAnimationHelper.SkeletonAnimation = null; behavior.SpineSkinHelper.SkeletonAnimation = null; } behavior.SpriteAnimationHelper.RemoveRenderer(ShadowSprite); }
public Actor(Device device, List <Outfit> outfits, ActorModel model, FigureLoader figureLoader, FigureFacade mainFigure, FigureFacade hairFigure, ActorBehavior behavior) { this.outfits = outfits; this.model = model; this.figureLoader = figureLoader; this.mainFigure = mainFigure; this.hairFigure = hairFigure; this.behavior = behavior; clothingFigures = new FigureFacade[0]; mainFigure.Animator = new MainFigureAnimator(this); figureGroup = new FigureGroup(device, mainFigure, new FigureFacade[0]); SyncFigureGroup(); }
/// <summary> /// Performs necessary steps to deselect the current squad. /// </summary> private void deselectSquad() { if (selectedSquad != null) { UnitIdleAnimationBehavior[] idles = selectedSquad.GetComponentsInChildren <UnitIdleAnimationBehavior>(); foreach (UnitIdleAnimationBehavior idle in idles) { idle.Active = false; } selectedSquad = null; } startingPoint = null; grid.HideMovePoints(); validTargets = null; }
/// <summary> /// Completes the combat, /// </summary> /// <param name="losingSquad"> /// Reference to the squad that lost the combat. /// </param> private void endCombat(CombatSquadBehavior losingSquad) { MonoBehaviour[] objects = GetComponentsInChildren <MonoBehaviour>(); for (int _i = (objects.Count() - 1); _i >= 0; _i--) { if (objects[_i].name == "__UNITBASE__") { DestroyImmediate(objects[_i].gameObject); } } if (losingSquad != null) { ActorBehavior actor = losingSquad.GetComponent <ActorBehavior>(); if (actor != null && grid.ignoreList.Contains(actor.currentMovePoint)) { grid.ignoreList.Remove(actor.currentMovePoint); } // Retrieve the game controller to determine which side the losing team was on. GameControllerBehaviour gameController = grid.GetComponent <GameControllerBehaviour>(); if (actor.theSide == GameControllerBehaviour.UnitSide.player) { gameController.playerTeamTotal--; } else { gameController.enemyTeamTotal--; } Destroy(losingSquad.gameObject); } foreach (NodeSkeletonBehavior node in unitPrefabs) { DestroyImmediate(node.gameObject); } this.offensiveSquad = null; this.defensiveSquad = null; GridBehavior.preCombat = false; HonorSystemBehavior.inCombat = true; GridBehavior.inCombat = false; AudioBehavior.inCombat = false; }
private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { StatusMultiple StatusMultiple = collision.gameObject.GetComponent <StatusMultiple>(); PlayerStatus Status = collision.gameObject.GetComponent <PlayerStatus>(); ActorBehavior Actor = collision.gameObject.GetComponent <ActorBehavior>(); AudioSource Audio = gameObject.AddComponent <AudioSource>(); if (ChangeGuns != null && ChangeGuns.GetComponent <ShooterBehavior>()) { Status.Guns = ChangeGuns; } if (GetSound != null) { Audio.PlayOneShot(GetSound); } gameObject.GetComponent <Renderer>().enabled = false; Actor.Life += AddLife; Actor.MaxLife += AddMaxlife; StatusMultiple.MulSpeed += AddMulSpeed; StatusMultiple.MulDamage += AddMulDamage; GameObject Script = new GameObject("ItemScript") as GameObject; ItemScriptAppears itemScript = Script.AddComponent <ItemScriptAppears>(); itemScript.text = GetScript; itemScript.font = Scriptfont; if (Actor.Energy < Actor.MaxEnergy * 2) { if (Actor.Energy >= Actor.MaxEnergy) { Actor.Energy += AddEnergy / 5; Actor.MaxEnergy += AddEnergy / 50; } if (Actor.Energy < Actor.MaxEnergy) { Actor.Energy += AddEnergy; } } Destroy(gameObject, GetSound.length); } }
// Use this for initialization void Start() { // Get ActorBehavior Script and gebing listening for events actBhvr = GetComponentInChildren<ActorBehavior>(); actBhvr.DidGetHit += ActBhvr_DidGetHit; ; actBhvr.DidHit += ActBhvr_DidHit; // Get Robot Sunc Behavior RbtSync = GetComponent<RobotSyncBehavior>(); // Get Input Scripts inputArray = GetComponents<InputManager>(); // Get Mesh Material meshMaterial = meshObj.GetComponent<Renderer>().material; // Set Up diferent colors origMeshColor = meshMaterial.color; stunMeshColor = Color.yellow; }
public override AIState DetermineCombatTarget() { targetActor = null; distanceToTarget = float.PositiveInfinity; MovePointBehavior movePoint = Actor.currentMovePoint; CombatSquadBehavior combatSquad = Actor.GetComponent<CombatSquadBehavior>(); if(combatSquad == null) { Debug.LogError(string.Format("AI Squad ({0}) does not have a CombatSquadBehavior!", Actor.transform.name)); Actor.actorHasMovedThisTurn = true; return AIState.PickingSquad; } int attackRange = combatSquad.Squad.Range; // Retrieve a list of nodes in range. List<MovePointBehavior> graph = new List<MovePointBehavior>(); movePoint.BuildGraph (attackRange, 0, grid, ref graph, true); // Iterate over the nodes to determine if any node has an enemy. foreach(MovePointBehavior node in graph) { ActorBehavior actorOnNode = gameController.GetActorOnNode(node); if(actorOnNode == null || (actorOnNode.theSide != GameControllerBehaviour.UnitSide.player)) continue; beginCombatWithTarget(actorOnNode); return AIState.WaitingForCombat; } return AIState.PickingSquad; }
private void ActBhvr_DidHit(ActorBehavior atckActBhvr, HitStats atckHitStats) { if(atckHitStats.WasBlocked) { // Adjust damage atckHitStats.DamageDealt = chipDamage; // Set pitch to very low and play Hit sound. cmbPitch = 0.5f; punchSndPlyr.pitch = cmbPitch; punchSndPlyr.PlayOneShot(punchSndArray[0]); // Apply block knockback; // Drop Combo cmbCount = 0; isComboing = false; cmbDmgMult = 1.0f; prvsHit = null; return; } // Get current hit key string curHit = atckHitStats.Key; // Checks for Sync-hit if (atckHitStats.ComboTiming < cmbThreshold) { // New hit must be different from precious if (curHit != prvsHit) { // Increase combo count cmbCount++; // Reset Combo Timer comboTimer = cmbTimeout; // First Combo Hit if (!isComboing) { // Combo Start isComboing = true; StartCoroutine(ComboTimer()); // Reset pitch and play first Sync-Hit sound. cmbPitch = 1.0f; punchSndPlyr.pitch = cmbPitch; punchSndPlyr.PlayOneShot(punchSndArray[0]); } else { // Increase pitch linearly cmbPitch += 0.2f; // Apply current pitch and play second+ hit sound; punchSndPlyr.pitch = cmbPitch; punchSndPlyr.PlayOneShot(punchSndArray[0]); // Cap Combo sound Pitch if (cmbPitch > 2.4f) cmbPitch = 2.4f; } // Combo Multiplyer progression cmbDmgMult = 1 + (Mathf.Pow(cmbCount, 2)) / 20; // Cap combo Multiplier if (cmbDmgMult > 2.0f) cmbDmgMult = 2.0f; // Updates Damage atckHitStats.DamageDealt *= cmbDmgMult; } else { //Sync hit, but same hit - Drop combo. cmbCount = 0; isComboing = false; cmbDmgMult = 1.0f; // Reset pitch and play first Sync-Hit sound. cmbPitch = 1.0f; punchSndPlyr.pitch = cmbPitch; punchSndPlyr.PlayOneShot(punchSndArray[0]); } } else // Failed sync hit or blocked hit - Drop combo { cmbCount = 0; isComboing = false; cmbDmgMult = 1.0f; } // Update Combo HUD otherHUD.ShowCombo(cmbCount); otherHUD.SetComboAlpha(1); // Updates previous Hit prvsHit = curHit; }
/// <summary> /// Enables the renderer on any nodes the unit can move to. /// </summary> /// <param name="actor">Actor associated with this movement attempt.</param> /// <param name="grid">Grid associated with the movement.</param> /// <param name="range">Maximum distance (in grid squares) to highlight.</param> public void HighlightValidNodes(ActorBehavior actor, GridBehavior grid, int range = -1) { int depth = 0; if(actor.currentMovePoint == null) { Debug.LogError("Current move point is null!"); return; } //int maxDistance = 0; CombatSquadBehavior csb = actor.GetComponent<CombatSquadBehavior>(); if (csb == null) Debug.LogWarning("Attempting to move a unit that does not have a squad associated!"); bool skipIgnoreList = false; if(range == -1) range = (csb == null ? 1 : csb.Squad.Speed); else skipIgnoreList = true; List<MovePointBehavior> moveGraph = new List<MovePointBehavior>(); actor.currentMovePoint.BuildGraph(range, depth, grid, ref moveGraph, skipIgnoreList); moveGraph.RemoveAt(0); foreach (MovePointBehavior node in moveGraph) node.renderer.enabled = true; }
private void ActBhvr_DidHit(ActorBehavior arg1, HitStats arg2) { Debug.Log(this.gameObject.name + "Hit"); // Call Hit Function here! }
// Use this for initialization void Start() { // Initialize Class Variables flashTime = 0.1f; isComboing = false; cmbCount = 0; cmbPitch = 0.8f; cmbDmgMult = 1.0f; cmbThreshold = 1.0f; // Get ActorBehavior Script and gebing listening for events actBhvr = GetComponentInChildren<ActorBehavior>(); actBhvr.DidGetHit += ActBhvr_DidGetHit; ; actBhvr.DidHit += ActBhvr_DidHit; // Get Robot Sunc Behavior rbtSync = GetComponent<RobotSyncBehavior>(); //Get the other robots HUD foreach (RobotSyncBehavior robot in GameObject.FindObjectsOfType<RobotSyncBehavior>()) { if (robot != this.rbtSync) { otherHUD = robot.GetHUD(); break; } } // Get Mesh Material meshMaterial = meshObj.GetComponent<Renderer>().material; // Set Up diferent colors origMeshColor = meshMaterial.color; dmgMeshColor = Color.red; blckMeshColor = Color.cyan; // Get Sound Player and sounds punchSndPlyr = GetComponent<AudioSource>(); punchSndArray = Resources.LoadAll<AudioClip>("Sounds/"); }
/// <summary> /// Simply delays until the combat sequence has finished, then moves to the Picking Squad state. /// </summary> public void UpdateState_WaitingForCombat() { if (GridBehavior.inCombat) return; selectedActor = null; State = AIState.PickingSquad; }
/// <summary> /// Iterates over the enemy's squads and selects the first active squad capable of moving. /// If all squads have moved, the turn is ended. /// </summary> public void UpdateState_PickingSquad() { foreach (ActorBehavior actor in gameController.enemyTeam) { if (!actor.actorHasMovedThisTurn) { selectedActor = actor; State = AIState.DetermineMovePoint; setCameraTarget(selectedActor.gameObject); return; } } State = AIState.WaitingForPlayer; setCameraTarget(null); gameController.EndTurn(); }
/// <summary> /// Waits for the left mouse button to be clicked, then performs a raycast to determine if the player has clicked /// on one of her own squads. /// </summary> /// <remarks> /// Transitions: /// Player Clicks Valid Squad -> SelectingMovement /// </remarks> private void updateSelectingUnit() { // Wait for the left mouse button to be pressed. if(Input.GetMouseButtonDown (0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Perform raycasting and store a list of all objects that have been selected. List<RaycastHit> hits = new List<RaycastHit>(); hits.AddRange(Physics.RaycastAll (ray)); // Iterate over the selection list to determine if the player has clicked on one of her squads. foreach(RaycastHit hitInfo in hits.OrderBy (l => l.distance)) { // Capture the actor behavior on the hit object. ActorBehavior actor = hitInfo.transform.GetComponent<ActorBehavior>(); if(actor == null) continue; // Ensure that the unit has not moved and belongs to the player. if(!actor.actorHasMovedThisTurn && actor.theSide == inputSide) { // Mark the actor as selected. selectedSquad = actor; startingPoint = actor.currentMovePoint; // Begin the scripted "Idle" animation. UnitIdleAnimationBehavior[] idles = selectedSquad.GetComponentsInChildren<UnitIdleAnimationBehavior>(); foreach(UnitIdleAnimationBehavior idle in idles) idle.Active = true; // Enable rendering of valid target movement nodes. if(actor.currentMovePoint != null) actor.currentMovePoint.HighlightValidNodes(actor, grid); // STATE CHANGE: SelectingUnit -> SelectingMovement controlState = GridControlState.SelectingMovement; break; } } } }
/// <summary> /// Determines the target for this squad. /// </summary> /// <returns>AI state the controller should enter after determining the target.</returns> public override AIState DetermineMovePoint() { MovePointBehavior movePoint = Actor.currentMovePoint; // Get a list of spaces that are within attack range (movement + range). CombatSquadBehavior combatSquad = Actor.GetComponent<CombatSquadBehavior>(); if(combatSquad == null) { Debug.LogError(string.Format("AI Squad ({0}) does not have a CombatSquadBehavior!", Actor.transform.name)); Actor.actorHasMovedThisTurn = true; return AIState.PickingSquad; } int attackRange = combatSquad.Squad.Range; int moveDistance = combatSquad.Squad.Speed; List<MovePointBehavior> pointsInRange = new List<MovePointBehavior>(); movePoint.BuildGraph(attackRange + moveDistance, 0, grid, ref pointsInRange, true); // Find the closest actor in attack range. foreach(MovePointBehavior node in pointsInRange) { ActorBehavior actorOnNode = gameController.GetActorOnNode(node); if(actorOnNode == null || (actorOnNode.theSide != GameControllerBehaviour.UnitSide.player)) continue; // If the distance to the target is less than the distance to the selected target, target it instead. float distance = Vector3.Distance(Actor.transform.position, actorOnNode.transform.position); if(distance < distanceToTarget) { targetActor = actorOnNode; distanceToTarget = distance; } } // If a target was found, move toward it. if(targetActor != null) { // Build a path to the actor. List<MovePointBehavior> pathList = movePoint.FindPath(targetActor.currentMovePoint, (moveDistance + attackRange), grid, true); // Remove the target's move point from the grid. pathList.RemoveAt (pathList.Count - 1); // Determine the excess items in the path list. int excess = pathList.Count - moveDistance; if(excess > 0) pathList.RemoveRange (pathList.Count - excess, excess); MovePointBehavior targetPoint = pathList[pathList.Count - 1]; // Determine the fastest path to the target point. pathList = movePoint.FindPath (targetPoint, moveDistance, grid); if(pathList != null) { Actor.pathList = pathList; Actor.canMove = true; grid.ignoreList.Remove (movePoint); grid.ignoreList.Add (targetPoint); Actor.actorHasMovedThisTurn = true; return AIState.WaitingForMove; } } else { // No target was found, so determine the closest target to move towards. foreach(ActorBehavior playerSquad in gameController.playerTeam) { float distance = Vector3.Distance(Actor.transform.position, playerSquad.transform.position); if(distance < distanceToTarget) { targetActor = playerSquad; distanceToTarget = distance; } } // Retrieve a list of all nodes within movement range. List<MovePointBehavior> nodesInRange = new List<MovePointBehavior>(); movePoint.BuildGraph(moveDistance, 0, grid, ref nodesInRange); // Cast a ray to the target and retrieve the farthest one that is in our movement range. Ray ray = new Ray(Actor.transform.position, (targetActor.transform.position - Actor.transform.position).normalized); // Perform raycasting and store a list of all objects that have been selected. List<RaycastHit> hits = new List<RaycastHit>(); hits.AddRange(Physics.RaycastAll (ray)); // Iterate over the selection list to determine if the player has clicked on one of her squads. foreach(RaycastHit hitInfo in hits.OrderBy (l => l.distance).Reverse()) { MovePointBehavior hitBehavior = hitInfo.transform.GetComponent<MovePointBehavior>(); if(hitBehavior == null || !nodesInRange.Contains (hitBehavior)) continue; // Target node has been found! Find a path to it. List<MovePointBehavior> pathList = movePoint.FindPath(hitBehavior, moveDistance, grid); if(pathList != null) { Actor.pathList = pathList; Actor.canMove = true; grid.ignoreList.Remove (movePoint); grid.ignoreList.Add (hitBehavior); Actor.actorHasMovedThisTurn = true; return AIState.WaitingForMove; } } } Actor.actorHasMovedThisTurn = true; return AIState.PickingSquad; }
//rect(left, top, width, height) void Start() { controller = GetComponent<playerController>(); behavior = GetComponent<ActorBehavior>(); Left = 0; Right = Screen.width; HorizMiddle = Screen.width/2; HorizQuarter = HorizMiddle/2; Top = 0; Bottom = Screen.height; VertMiddle = Screen.height/2; VertQuarter = VertMiddle/2; }
/// <summary> /// Performs necessary steps to deselect the current squad. /// </summary> private void deselectSquad() { if(selectedSquad != null) { UnitIdleAnimationBehavior[] idles = selectedSquad.GetComponentsInChildren<UnitIdleAnimationBehavior>(); foreach(UnitIdleAnimationBehavior idle in idles) idle.Active = false; selectedSquad = null; } startingPoint = null; grid.HideMovePoints(); validTargets = null; }
/* static */ public void DepthFirstSearch(ActorBehavior actor) { foreach (MovePointBehavior node in actor.currentMovePoint.neighborList) { if (!node) continue; node.renderer.enabled = true; foreach (MovePointBehavior secondNode in node.neighborList) { if (!secondNode) continue; secondNode.renderer.enabled = true; } } }