private void EvaluateSituation() { if (Target != null) { targetDistance = Vector3.Distance(transform.position, Target.transform.position); if (targetDistance < attackDistance) { if (!canBackpedal) { behavior = AIBehaviorExtensions.GetInRangeAndAttackBehavior; } else if (targetDistance < attackDistance - safetyZone && sensor.GotVisual) { behavior = AIBehaviorExtensions.BackpedalBehavior; } else { behavior = AIBehaviorExtensions.GetInRangeAndAttackBehavior; } } else { behavior = AIBehaviorExtensions.GetInRangeAndAttackBehavior; } } }
void Awake() { col = GetComponent <Collider2D>(); aiBehavior = GetComponentInParent <AIBehavior>(); Debug.Assert(aiBehavior, "Wrong initial parameters"); col.enabled = false; }
void SwitchItemInList(AIBehavior ai, int a, int b) { AIState temp = ai.StatesList[a]; ai.StatesList[a] = ai.StatesList[b]; ai.StatesList[b] = temp; }
void Awake() { // if the singleton hasn't been initialized yet if (instance != null && instance != this) { Destroy(this.gameObject); } instance = this; if (SaveData.CurrentMatchExists) { player = new PlayerMatchInstance(SaveData.current.playerSave); cpu = new PlayerMatchInstance(SaveData.current.calendar.GetTournament().currentMatch.cpuPlayer); } else { player = new PlayerMatchInstance("JeanPlayer"); cpu = new PlayerMatchInstance("EdouardCPU"); } pointHistory = new PointHistory(); aIBehavior = new EasyAIBehavior(eventReader); StartGame(); }
public void DecideAndQueueAction() { if (!this.IsActive) { return; } foreach (var beh in AIBehaviors.GetComponents <AIBehavior>()) { if (beh == activeBehavior) { if (beh.ShouldDeactivate()) { continue; } else { break; } } if (beh.ShouldActivate()) { Debug.LogFormat("[{0}] ({1}) activated", this.Name, beh.GetType().Name); activeBehavior = beh; break; } } Debug.LogFormat("[{0}] ({1}) deciding", this.Name, activeBehavior.GetType().Name); activeBehavior.DecideAndQueueAction(); }
IEnumerator IEStagger(float duration, float waitTime = 0f) { //wait before staggering(to fine-tune animations) //if(waitTime > 0f) yield return(new WaitForSeconds(waitTime)); //prevent player control while staggered setControlAllowedIfPlayer(false, false); _animator.SetBool(AnimationHashHelper.PARAM_STAGGERED, true); //adds delay when ai is attacked AIBehavior aib = GetComponent <AIBehavior> (); if (aib != null) { aib.IsBehaviorAllowed = false; } yield return(new WaitForSeconds(duration)); if (aib != null) { //dev aib.IsBehaviorAllowed = true; } _animator.SetBool(AnimationHashHelper.PARAM_STAGGERED, false); if (_health > 0) { setControlAllowedIfPlayer(true, false); } }
public static List <List <TowerBehavior> > InsertionSortUnits(AIBehavior AI, Dictionary <int, List <TowerBehavior> > dictionary) { List <List <TowerBehavior> > currentTowers = new List <List <TowerBehavior> >(dictionary.Values); if (currentTowers.Count > 1) { for (int i = 1; i < currentTowers.Count; i++) { List <TowerBehavior> listInQuestion = new List <TowerBehavior>(); listInQuestion.AddRange(currentTowers[i]); int previous = i - 1; while (previous >= 0 && currentTowers[previous][0].StationedUnits > listInQuestion[0].StationedUnits) { currentTowers[previous + 1].Clear(); currentTowers[previous + 1].AddRange(currentTowers[previous]); previous--; } currentTowers[previous + 1].Clear(); currentTowers[previous + 1].AddRange(listInQuestion); } return(currentTowers); } //if count is 1 return(currentTowers); }
public void DecideGoalBehavior() { lastBehaviorDecision = GameTimer.Instance.GetFrameTimestamp(); IReadonlyListX <DecisionContext> goalContexts = activeGoal.GetExecutionContexts(entity); float maxScore = float.MinValue; activeContext = null; activeBehavior = null; for (int i = 0; i < behaviors.Count; i++) { AIBehavior behavior = behaviors[i]; if (!behavior.CanSatisfyGoalType(activeGoal.goalType)) { // continue; } DecisionContext context; float score = AIUtil.Score(goalContexts, behavior.considerations, maxScore, out context); if (score > maxScore) { maxScore = score; activeBehavior = behavior; activeContext = context; } } }
public static List <List <TowerBehavior> > InsertionSortDistance(AIBehavior AI, Dictionary <int, List <TowerBehavior> > dictionary) { List <List <TowerBehavior> > currentTowers = new List <List <TowerBehavior> >(dictionary.Values); if (currentTowers.Count > 1) { for (int i = 1; i < currentTowers.Count; i++) { List <TowerBehavior> listInQuestion = new List <TowerBehavior>(); listInQuestion.AddRange(currentTowers[i]); int previous = i - 1; while (previous >= 0 && DistanceRoundInt(Vector3.Distance(currentTowers[previous][0].transform.position, AI.myTower.transform.position)) > DistanceRoundInt(Vector3.Distance(listInQuestion[0].transform.position, AI.myTower.transform.position))) { currentTowers[previous + 1].Clear(); currentTowers[previous + 1].AddRange(currentTowers[previous]); previous--; } currentTowers[previous + 1].Clear(); currentTowers[previous + 1].AddRange(listInQuestion); } return(currentTowers); } //if count is 1 return(currentTowers); }
public void Initialize(AIBehavior aIBehavior) { behaviour = aIBehavior; RefreshSwitchDictionary(); RefreshActionDictionary(); //RefreshStateDictionary(); }
void OnEnable() { if (target == null) { return; } SkipPropertyList.Add("x"); SkipPropertyList.Add("y"); SkipPropertyList.Add("z"); SkipPropertyList.Add("StartTime"); SkipPropertyList.Add("EndTime"); SkipPropertyList.Add("data"); BoldLabelPropertyList.Add("Switches"); BoldMiniLabelPropertyList.Add("SwitchCondition"); BoldMiniLabelPropertyList.Add("PossibleNextStates"); m_Name = serializedObject.FindProperty("name"); AIBehavior = (AIBehavior)target; for (int i = 0; i < AIBehavior.StatesList.Count; i++) { AIBehavior.StatesList[i].Index = i; for (int j = 0; j < AIBehavior.StatesList[i].Actions.Count; j++) { AIBehavior.StatesList[i].Actions[j].ActionSettings.StartTime = 0; AIBehavior.StatesList[i].Actions[j].ActionSettings.EndTime = Mathf.Infinity; } } }
public virtual bool IsCompositeConditionMatched(CompositeCondition compositeCondition, CompositeConditionWrapper compositeConditionWrapper, AIBehavior behavior) { bool ret = false; switch (compositeCondition.Operator) { case LogicConjunction.None: ret = IsConditionEntityMatched(compositeCondition.Entity1, compositeConditionWrapper, behavior); break; case LogicConjunction.And: ret = IsConditionEntityMatched(compositeCondition.Entity1, compositeConditionWrapper, behavior); if (ret) { ret = IsConditionEntityMatched(compositeCondition.Entity2, compositeConditionWrapper, behavior); } break; case LogicConjunction.Or: ret = IsConditionEntityMatched(compositeCondition.Entity1, compositeConditionWrapper, behavior); if (ret == false) { ret = IsConditionEntityMatched(compositeCondition.Entity2, compositeConditionWrapper, behavior); } break; } return(ret); }
/// <summary> ///This function is called to find a tower to send the troops /// </summary> public TowerBehavior FindTowerToSendTroops(AIBehavior attackingAI) { //gives me a dictionary with numUnits associated with their towers lowest num being at the 0 element List <List <TowerBehavior> > UnitList = attackingAI.GetUnitPriority(); //gives me a dictionary with distance associated with the tower from the origin. smallest distance is the zero element List <List <TowerBehavior> > DistanceList = attackingAI.GetDistancePriority(); //create a final list that holds a tower and it's total score from both dictionaries Dictionary <TowerBehavior, int> finalDict = new Dictionary <TowerBehavior, int>(); //this variable is used for the value that we will give each tower //we put it outside the foreach loop so that towers in the same //list are given the same value int counter = 0; //go through each list in the unit dictionary foreach (List <TowerBehavior> list in UnitList) { //go through each tower through each list foreach (TowerBehavior tower in list) { //add that tower the the final dictionary with its value finalDict.Add(tower, counter); } //increment counter after going through the list counter++; } //reset the counter counter = 0; //go through each list in the distance dictionary foreach (List <TowerBehavior> list in DistanceList) { //go through each tower in each list foreach (TowerBehavior tower in list) { //if the final dictionary already contains the tower if (finalDict.ContainsKey(tower)) { //add the new counter to the final value finalDict[tower] += (counter); } //if not, then something is wrong else { #if Unity_Editor Debug.LogError("DICTIONARY DOESN'T CONTAIN TOWER ALREADY,RETURNING NULL"); #endif return(null); } } //increment the counter counter++; } //send the dictionary to the function so that the tower can actually be chosen return(FindTowerToAttack(finalDict)); }
public virtual IEnumerator Start_MoveToWaypoint(AIBehavior behavior) { MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; WayPoint[] wpArray = WayPoint.GetWaypoints(behavior.WaypointNames); WayPoint wp = Util.RandomFromArray <WayPoint>(wpArray); behavior.selectedWaypoint = wp; StartNavigation(behavior.selectedWaypoint.transform, true, MoveData); float lastScanEndConditionTime = Time.time; while (true) { if (Halt) { yield return(null); continue; } //if this behavior's end condition matches, end this behavior if ((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if (CheckAlternateBehaviorCondition(behavior)) { break; } } yield return(null); } StopBehavior(behavior); }
/// <summary> /// Start behave move to.transform target. /// The behavior is terminated by itself, if AI reaches enough close to the target transform. /// </summary> /// <returns></returns> public virtual IEnumerator Start_MoveToTransform(AIBehavior behavior) { MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; StartNavigation(behavior.MoveToTarget, true, MoveData); float lastScanEndConditionTime = Time.time; while (true) { if (Halt) { yield return(null); continue; } //if this behavior's end condition matches, end this behavior if ((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if (CheckAlternateBehaviorCondition(behavior)) { break; } } float distance = Util.DistanceOfCharacters(gameObject, behavior.MoveToTarget.gameObject); if (distance <= 0.5f) { break; } yield return(null); } StopBehavior(behavior); }
void CharacterInitialize(Sprite mugShotArg, string name, AIBehavior behavior) { mugShot.sprite = mugShotArg; characterName = name; nameText.text = characterName; aiBehavior = behavior; }
/// <summary> /// Stop a behavior. /// By default, the coroutine to stop = "Stop_" + behavior.Type.ToString(), offspring can /// override to define a new rule. /// </summary> /// <param name="behavior"></param> /// <returns></returns> /// public override void StopBehavior(AIBehavior behavior) { //preserve the last start time behavior.LastExecutionTime = Time.time; string Coroutine = "Stop_" + behavior.Type.ToString(); //By defaut, set the behavior phase = sleeping at StopBehavior() behavior.Phase = AIBehaviorPhase.Sleeping; foreach (string endMessage in behavior.MessageAtEnd) { SendMessage(endMessage); } foreach (GameEvent _event in behavior.GameEventAtEnd) { LevelManager.OnGameEvent(_event, this); } StartCoroutine(Coroutine, behavior); //Start next behavior string NextBehavior = behavior.NextBehaviorName; if (NextBehavior == string.Empty) { Debug.LogError("NextBehavior of behavior: " + behavior.Name + " is empty !"); } StartBehavior(this.behaviorDict[behavior.NextBehaviorName]); }
/// <summary> /// Execute a behavior. /// By default, the coroutine to start is the same name to behavior.Type.ToString(), offspring can /// override to define a new rule. /// </summary> /// <param name="behavior"></param> /// <returns></returns> public override void StartBehavior(AIBehavior behavior) { if (PrintDebugMessage) { Debug.Log("Now start behavior:" + behavior.Name); } //Rule: behavior start coroutine = "Start_" + BehaviorType string Coroutine = "Start_" + behavior.Type.ToString(); behavior.ExecutionCounter++; //preserve the start time behavior.StartTime = Time.time; //By defaut, set the behavior phase = running at StartBehavior() behavior.Phase = AIBehaviorPhase.Running; CurrentBehavior = behavior; foreach (string startMessage in behavior.MessageAtStart) { SendMessage(startMessage); } foreach (GameEvent _event in behavior.GameEventAtStart) { LevelManager.OnGameEvent(_event, this); } StartCoroutine(Coroutine, behavior); }
void Start() { fullAmmo = ammo; audioSrouce = (audioSrouce == null) ? GetComponent <AudioSource>() : audioSrouce; behavior = (behavior == null) ? GetComponent <AIBehavior>() : behavior; animator = (animator == null) ? GetComponent <AIAnimator>() : animator; }
// [MenuItem("Component/AI/EditCondition")] // public static void init () // { // ConditionEditorWindow window = (ConditionEditorWindow)EditorWindow.GetWindow (typeof(ConditionEditorWindow)); // window.title = "Root composite condition"; // } public static void DisplayConditionEditorWindow(AIEditor aiEditor, AIBehavior aiBehavior) { AlternateBehaviorEditorWindow window = (AlternateBehaviorEditorWindow)EditorWindow.GetWindow (typeof(AlternateBehaviorEditorWindow)); window.aiBehavior = aiBehavior; window.aiEditor = aiEditor; window.Show (); }
private bool attacking = false; // indicates if this enemy is attacking /* * Enemy * * Parameters: A list of components which are added to this object, the AIBehavior that belongs to this object * Purpose: creates a new Enemy */ public Enemy( List <EnemyBehavior> components, AIBehavior intel) : base() { enemyComponents = components; intelComponent = intel; collisionBehaviors = new List <CollisionBehavior>(); }
/// <summary> /// 1. Start A* pathfind daemon routines. /// 2. Start the first (default) AIBehavior. /// </summary> public override void StartAI() { Unit.CurrentAI = this; AIBehavior firstBehavior = this.behaviorDict[FirstBehavior]; this.StartBehavior(firstBehavior); this.enabled = true; }
/// <summary> /// Stop behave move at direction. /// </summary> /// <returns></returns> public virtual IEnumerator Stop_MoveAtDirection(AIBehavior behavior) { MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; animation.Stop(MoveData.AnimationName); StopCoroutine("Start_MoveAtDirection"); yield break; }
void Start() { anim = (anim == null) ? GetComponent <Animator>() : anim; agent = (agent == null) ? GetComponent <NavMeshAgent>() : agent; behavior = (behavior == null) ? GetComponent <AIBehavior>() : behavior; health = (health == null) ? GetComponent <Health>() : health; lastHealth = health.GetHealth(); groundRaycast = (groundRaycast == null) ? transform : groundRaycast; }
/// <summary> /// Stop behave stopping move to. /// </summary> /// <returns></returns> public virtual IEnumerator Stop_MoveToTransform(AIBehavior behavior) { StopNavigation(); MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; animation.Stop(MoveData.AnimationName); StopCoroutine("Start_MoveToTransform"); yield return(null); }
/// <summary> /// Stop Idle. /// </summary> /// <returns></returns> public virtual IEnumerator Stop_Idle(AIBehavior behavior) { // Debug.Log("Stop behavior:" + behavior.Name + " .IdleDataName:" + behavior.IdleDataName); StopCoroutine("Start_Idle"); string IdleAnimationName = Unit.IdleDataDict[behavior.IdleDataName].AnimationName; animation.Stop(IdleAnimationName); yield return(null); }
// [MenuItem("Component/AI/EditCondition")] // public static void init () // { // ConditionEditorWindow window = (ConditionEditorWindow)EditorWindow.GetWindow (typeof(ConditionEditorWindow)); // window.title = "Root composite condition"; // } public static void DisplayConditionEditorWindow(AIEditor aiEditor, AIBehavior aiBehavior) { AlternateBehaviorEditorWindow window = (AlternateBehaviorEditorWindow)EditorWindow.GetWindow(typeof(AlternateBehaviorEditorWindow)); window.aiBehavior = aiBehavior; window.aiEditor = aiEditor; window.Show(); }
void Awake() { rb = GetComponent <Rigidbody2D>(); follow = new Pursue(transform, slowRadius, targetRadius, accelTime, maxSpeed, maxAccel, maxPredict); face = new Face(transform, targetDistance, slowDistance, maxOmega, maxAlpha, timeToTarget); congregate = new Arrive(transform, slowRadius, targetRadius, accelTime, maxSpeed, maxAccel); separate = new Separate(transform, maxAccel, separateCastRadius); cg = FindObjectOfType <CGScript>().gameObject; }
// Start is called before the first frame update protected virtual void Start() { _velocity = Vector3.zero; _behavior = GetComponent <AIBehavior>(); if (_behavior != null) { _behavior.Init(this); } }
public static TreeIterationResult iterate(AIBehavior p_aiBehavior) { IAIBehaviorProvider l_aiBehaviorProvider = p_aiBehavior.IAIBehaviorProvider; DecisionTree l_decisionTree = DecisionTree.alloc(); l_aiBehaviorProvider.buildDecisionTree(l_decisionTree, p_aiBehavior.AssociatedEntity); RefList <AIDecisionTreeChoice> l_choices = Traversal.traverseDecisionTree(l_decisionTree); ref AIDecisionTreeChoice l_choice = ref l_aiBehaviorProvider.get_choicePicking().Invoke(l_choices, p_aiBehavior.AssociatedEntity);
public void ReactToHit() { AIBehavior behavior = GetComponent <AIBehavior>(); if (behavior != null) { behavior.SetAlive(false); } StartCoroutine(Die()); }
/// <summary> /// Start behave move to.transform target. /// The behavior is terminated by itself, if AI reaches enough close to the target transform. /// </summary> /// <returns></returns> public virtual IEnumerator Start_MoveToTransform(AIBehavior behavior) { MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; StartNavigation(behavior.MoveToTarget, true, MoveData); float lastScanEndConditionTime = Time.time; while (true) { if (Halt) { yield return null; continue; } //if this behavior's end condition matches, end this behavior if((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if(CheckAlternateBehaviorCondition(behavior)) { break; } } float distance = Util.DistanceOfCharacters(gameObject, behavior.MoveToTarget.gameObject); if (distance <= 0.5f) { break; } yield return null; } StopBehavior(behavior); }
/// <summary> /// Start behave move at direction. /// </summary> /// <returns></returns> public virtual IEnumerator Start_MoveAtDirection(AIBehavior behavior) { Vector3 direction = behavior.IsWorldDirection ? behavior.MoveDirection : transform.TransformDirection(behavior.MoveDirection); MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; Vector3 velocity = direction.normalized * MoveData.MoveSpeed; float LastCheckEndConditionTime = 0; while (true) { if (Halt) { yield return null; continue; } //if this behavior's end condition matches, end this behavior if( (Time.time - LastCheckEndConditionTime) >= behavior.AlterBehaviorInterval) { LastCheckEndConditionTime = Time.time; if(CheckAlternateBehaviorCondition(behavior)) { break; } } if(MoveData.UseGravityWhenMoving) { controller.SimpleMove(velocity); } else { controller.Move(velocity * Time.deltaTime); } animation.CrossFade(MoveData.AnimationName); yield return null; } StopBehavior(behavior); }
public virtual IEnumerator Start_HoldPosition(AIBehavior behavior) { Vector3 HoldPos = transform.position; while (true) { if (Vector3.Distance(transform.position, HoldPos) > behavior.HoldRadius) { } yield return null; } }
/// <summary> /// Execute a behavior. /// By default, the coroutine to start is the same name to behavior.Type.ToString(), offspring can /// override to define a new rule. /// </summary> /// <param name="behavior"></param> /// <returns></returns> public override void StartBehavior(AIBehavior behavior) { if(PrintDebugMessage) { Debug.Log("Now start behavior:" + behavior.Name); } //Rule: behavior start coroutine = "Start_" + BehaviorType string Coroutine = "Start_" + behavior.Type.ToString(); behavior.ExecutionCounter++; //preserve the start time behavior.StartTime = Time.time; //By defaut, set the behavior phase = running at StartBehavior() behavior.Phase = AIBehaviorPhase.Running; CurrentBehavior = behavior; foreach (string startMessage in behavior.MessageAtStart) { SendMessage(startMessage); } foreach( GameEvent _event in behavior.GameEventAtStart) { LevelManager.OnGameEvent(_event, this); } StartCoroutine(Coroutine, behavior); }
/// <summary> /// Default check value comparision condition routine. /// Offspring class should override this method to check custom value comparision condition. /// </summary> /// <param name="AIBehaviorCondition"></param> /// <returns></returns> public virtual bool CheckValueComparisionCondition(AtomConditionData AIBehaviorCondition, AIBehavior behavior) { bool ret = false; float LeftValue = 0; float RightValue = AIBehaviorCondition.RightValueForComparision; bool ShouldCompare = false; switch (AIBehaviorCondition.ValueComparisionCondition) { //Check if any enemy closer than AIBehaviorCondition.RightValueForComparision case AIValueComparisionCondition.NearestEnemyDistance: Transform NearestEnemy = null; ShouldCompare = FindClosestEnemyAround(this.DetectiveRange, out NearestEnemy); LeftValue = ShouldCompare ? Util.DistanceOfCharacters(gameObject, NearestEnemy.gameObject) : 0; break; //Check if any enemy farer than AIBehaviorCondition.RightValueForComparision case AIValueComparisionCondition.FarestEnemyDistance: Transform FarestEnemy = null; ShouldCompare = FindClosestEnemyAround(this.DetectiveRange, out FarestEnemy); LeftValue = ShouldCompare ? Util.DistanceOfCharacters(gameObject, FarestEnemy.gameObject) : 0; break; case AIValueComparisionCondition.HPPercentage: ShouldCompare = true; LeftValue = Unit.HP / Unit.MaxHP; break; case AIValueComparisionCondition.CurrentTargetHPPercentage: ShouldCompare = CurrentTarget != null || FindTarget(this.DetectiveRange); LeftValue = ShouldCompare ? CurrentTarget.GetComponent<UnitHealth>().GetCurrentHP() / CurrentTarget.GetComponent<UnitHealth>().GetMaxHP() : 0; if (PrintDebugMessage) Debug.Log("Left value:" + LeftValue + " rightValue:" + RightValue); break; case AIValueComparisionCondition.BehaviorLastExecutionInterval: ShouldCompare = true; float LastExecutionTimeInterval = Time.time - behavior.LastExecutionTime; LeftValue = LastExecutionTimeInterval; break; case AIValueComparisionCondition.CurrentTagetDistance: ShouldCompare = (CurrentTarget != null || FindTarget(this.DetectiveRange)); LeftValue = ShouldCompare ? Util.DistanceOfCharacters(gameObject, CurrentTarget.gameObject) : 0; break; case AIValueComparisionCondition.ExeuctionCount: ShouldCompare = true; LeftValue = behavior.ExecutionCounter; break; case AIValueComparisionCondition.RandomValue: ShouldCompare = true; // Random.seed = System.DateTime.Now.Millisecond; LeftValue = Random.Range(0, 100); break; case AIValueComparisionCondition.BehaveTime: ShouldCompare = true; LeftValue = Time.time - behavior.StartTime; break; case AIValueComparisionCondition.AttackCount: ShouldCompare = true; LeftValue = this.Unit.AttackCounter; break; case AIValueComparisionCondition.DoDamageCount: ShouldCompare = true; LeftValue = this.Unit.DoDamageCounter; break; case AIValueComparisionCondition.LastConditionMatchTimeInterval: ShouldCompare = true; LeftValue = Time.time - AIBehaviorCondition.PreviousConditionTrueTime; break; case AIValueComparisionCondition.WaypointDistance: ShouldCompare = behavior.selectedWaypoint != null; LeftValue = Util.DistanceOfCharacters(this.gameObject, behavior.selectedWaypoint.gameObject); break; default: Debug.LogError("GameObject:" + this.gameObject.name + " - unsupported value comparision condition:" + AIBehaviorCondition.ValueComparisionCondition.ToString()); break; } if (ShouldCompare) { ret = Util.CompareValue(LeftValue, AIBehaviorCondition.ValueOperator, RightValue); } //if the atom condition is true, set the current time in PreviousConditionTrueTime variable. if(ret) { AIBehaviorCondition.PreviousConditionTrueTime = Time.time; } return ret; }
/// <summary> /// Default check boolean condition routine. /// Offspring class should override this method to check custom boolean condition. /// </summary> /// <param name="AIBehaviorCondition"></param> /// <returns></returns> public virtual bool CheckBooleanCondition(AtomConditionData AIBehaviorCondition, AIBehavior behavior) { bool ret = false; bool LeftValue = false; switch (AIBehaviorCondition.BooleanCondition) { case AIBooleanConditionEnum.AlwaysTrue: LeftValue = true; break; //See if there's any enemy in offensive range? case AIBooleanConditionEnum.EnemyInOffensiveRange: LeftValue = FindEnemyAround(this.OffensiveRange); break; //See if there's any enemy in detective range? case AIBooleanConditionEnum.EnemyInDetectiveRange: LeftValue = FindEnemyAround(this.DetectiveRange); break; //See if current transform located within the predefined area? case AIBooleanConditionEnum.InArea: LeftValue = Util.IsTransformInsideBounds(transform, AIBehaviorCondition.CheckArea); break; //See if the CurrentTarget's gameObject layer within the layermask case AIBooleanConditionEnum.CurrentTargetInLayer: LeftValue = (CurrentTarget == null && FindTarget(OffensiveRange) == false) ? false : Util.CheckLayerWithinMask(CurrentTarget.gameObject.layer, AIBehaviorCondition.LayerMaskForComparision); break; case AIBooleanConditionEnum.LatestBehaviorNameIs: if(this.CurrentBehavior == null) LeftValue = false; else LeftValue = (AIBehaviorCondition.StringValue == this.CurrentBehavior.Name); break; case AIBooleanConditionEnum.LastestBehaviorNameIsOneOf: if(this.CurrentBehavior == null) { LeftValue = false; } else { LeftValue = Util.ArrayContains<string>(AIBehaviorCondition.StringValueArray, this.CurrentBehavior.Name); } break; default: Debug.LogError("GameObject:" + this.gameObject.name + " - Unsupported boolean condition:" + AIBehaviorCondition.BooleanCondition.ToString()); break; } ret = AIBehaviorCondition.BooleanOperator == BooleanComparisionOperator.IsTrue ? LeftValue : !LeftValue; return ret; }
/// <summary> /// Scans the alternate behavior condition of the given behavior. /// Return true if one of the alternate behavior condition matches, and assign next behavior to behavior.NextBehavior varaible. /// </summary> public virtual bool CheckAlternateBehaviorCondition(AIBehavior behavior) { bool hasConditionMatched = false; behavior.NextBehaviorName = string.Empty; for(int i=0; i<behavior.alternateBehaviorConditionArray.Length; i++) { AlternateBehaviorData alternateBehaviorData = behavior.alternateBehaviorConditionArray[i]; bool IsAlterBehaviorConditionMatched = CheckConditionWrapper( alternateBehaviorData.AlternateCondition, behavior); if(this.PrintDebugMessage) { Debug.Log("AlernateBehavior name:" + alternateBehaviorData.Name + " is matched:" + IsAlterBehaviorConditionMatched); } if(IsAlterBehaviorConditionMatched){ behavior.NextBehaviorName = alternateBehaviorData.NextBehaviorName; hasConditionMatched = true; // Debug.Log("At frame:" + Time.frameCount + " behavior:" + behavior.Name + " condition match at: " + alternateBehaviorData.Name + " alter to next behavior:" + alternateBehaviorData.NextBehaviorName); break; } } return hasConditionMatched; }
IEnumerator Idle() { if(CanSeePlayer() || myTarget != null) { behave = AIBehavior.pursue; } yield return null; }
IEnumerator Pursue() { if(InMeleeRange() && !inAttackDelay ) { behave = AIBehavior.attack; yield return null; } else { TraverseToTarget(); behave = AIBehavior.idle; } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Make and instance of the tree based ont he AI type assigned, if no type matches give it the default mob AI. */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Start() { methodLibrary = gameObject.GetComponent<AIBehavior> (); if(behaviorType == "mob"){ dPath = new DTree<BranchLogic> (new BranchLogic(methodLibrary.MaxWander)); coreTreeSetup (); } else if(behaviorType == "boss"){ dPath = new DTree<BranchLogic> (new BranchLogic(methodLibrary.MaxWander)); coreTreeSetup (); } else{ dPath = new DTree<BranchLogic> (new BranchLogic(methodLibrary.MaxWander)); coreTreeSetup (); } }
void Start() { methodLibrary = gameObject.GetComponent<AIBehavior> (); dPath = new DTree<BranchLogic> (new BranchLogic(methodLibrary.MaxWander)); coreTreeSetup (); }
public override void StartBehavior(AIBehavior behavior) { }
public virtual void Start_SwitchToAI(AIBehavior behavior) { string NextAIName = Util.RandomFromArray(behavior.SwitchToAIName); this.Unit.SwitchAI(NextAIName); }
private bool IsConditionEntityMatched(ConditionEntity conditionEntity, CompositeConditionWrapper compositeConditionWrapper, AIBehavior behavior) { bool ret = false; switch(conditionEntity.EntityType) { case ConditionEntityType.AtomCondition: AtomConditionData atomCondition = compositeConditionWrapper.AtomConditionDataDict[conditionEntity.EntityReferenceId]; ret = CheckAtomCondition(atomCondition, behavior); break; case ConditionEntityType.ReferenceToComposite: CompositeCondition compositeCondition = compositeConditionWrapper.CompositeConditionDict[conditionEntity.EntityReferenceId]; ret = IsCompositeConditionMatched(compositeCondition, compositeConditionWrapper, behavior); break; } return ret; }
/// <summary> /// Stop a behavior. /// By default, the coroutine to stop = "Stop_" + behavior.Type.ToString(), offspring can /// override to define a new rule. /// </summary> /// <param name="behavior"></param> /// <returns></returns> /// public override void StopBehavior(AIBehavior behavior) { //preserve the last start time behavior.LastExecutionTime = Time.time; string Coroutine = "Stop_" + behavior.Type.ToString(); //By defaut, set the behavior phase = sleeping at StopBehavior() behavior.Phase = AIBehaviorPhase.Sleeping; foreach (string endMessage in behavior.MessageAtEnd) { SendMessage(endMessage); } foreach( GameEvent _event in behavior.GameEventAtEnd) { LevelManager.OnGameEvent(_event, this); } StartCoroutine(Coroutine, behavior); //Start next behavior string NextBehavior = behavior.NextBehaviorName; if(NextBehavior == string.Empty) { Debug.LogError("NextBehavior of behavior: " + behavior.Name + " is empty !"); } StartBehavior(this.behaviorDict[behavior.NextBehaviorName]); }
/// <summary> /// Check if the AIBehavior condition is true /// </summary> /// <param name="AIBehaviorCondition"></param> /// <returns></returns> public virtual bool CheckAtomCondition(AtomConditionData AIBehaviorCondition, AIBehavior behavior) { bool ret = false; switch (AIBehaviorCondition.ConditionType) { case AIBehaviorConditionType.Boolean: ret = CheckBooleanCondition(AIBehaviorCondition, behavior); break; case AIBehaviorConditionType.ValueComparision: ret = CheckValueComparisionCondition(AIBehaviorCondition, behavior); break; } return ret; }
public virtual IEnumerator Stop_Attack(AIBehavior behavior) { StopNavigation(); yield return null; }
public virtual bool CheckConditionWrapper(CompositeConditionWrapper compositeConditionWrapper,AIBehavior behavior) { bool ret = false; ret = IsCompositeConditionMatched(compositeConditionWrapper.RootCompositeCondition, compositeConditionWrapper, behavior); return ret; }
public virtual IEnumerator Stop_HoldPosition(AIBehavior behavior) { StopCoroutine("Start_HoldPosition"); yield return null; }
public virtual bool IsCompositeConditionMatched(CompositeCondition compositeCondition, CompositeConditionWrapper compositeConditionWrapper, AIBehavior behavior) { bool ret = false; switch(compositeCondition.Operator) { case LogicConjunction.None: ret = IsConditionEntityMatched(compositeCondition.Entity1,compositeConditionWrapper,behavior); break; case LogicConjunction.And: ret = IsConditionEntityMatched(compositeCondition.Entity1,compositeConditionWrapper,behavior); if(ret) ret = IsConditionEntityMatched(compositeCondition.Entity2,compositeConditionWrapper,behavior); break; case LogicConjunction.Or: ret = IsConditionEntityMatched(compositeCondition.Entity1,compositeConditionWrapper,behavior); if(ret == false) ret = IsConditionEntityMatched(compositeCondition.Entity2,compositeConditionWrapper,behavior); break; } return ret; }
/// <summary> /// Stop Idle. /// </summary> /// <returns></returns> public virtual IEnumerator Stop_Idle(AIBehavior behavior) { // Debug.Log("Stop behavior:" + behavior.Name + " .IdleDataName:" + behavior.IdleDataName); StopCoroutine("Start_Idle"); string IdleAnimationName = Unit.IdleDataDict[behavior.IdleDataName].AnimationName; animation.Stop(IdleAnimationName); yield return null; }
/// <summary> /// Start behave attack /// </summary> /// <param name="behavior"></param> /// <returns></returns> public virtual IEnumerator Start_Attack(AIBehavior behavior) { AttackData attackData = null; float lastScanEndConditionTime = Time.time; while (true) { //If no target is found, do nothing if (Halt || CurrentTarget == null) { yield return null; continue; } //Get attack data if(behavior.UseRandomAttackData == false) { attackData = Unit.AttackDataDict[behavior.AttackDataName]; } else { string attackDataName = Util.RandomFromArray<string>(behavior.AttackDataNameArray); attackData = Unit.AttackDataDict[attackDataName]; } //if this behavior's end condition matches, end this behavior if((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if(CheckAlternateBehaviorCondition(behavior)) { break; } } //Animating attack string AttackAnimationName = attackData.AnimationName; //If can see target, and target distance <= AttackableRange, do this: //1. Face to target //2. Check last attack time against attack interval //3. if #2 pass, animating, send hit message if (this.CanSeeCurrentTarget && CurrentTargetDistance <= attackData.AttackableRange) { if(attackData.LookAtTarget) { transform.LookAt(new Vector3(CurrentTarget.position.x, transform.position.y, CurrentTarget.position.z)); } //If hitTriggerType is HitTriggerType.ByAnimationEvent, the function will be invoked by animation event if(attackData.hitTriggerType == HitTriggerType.ByTime) { SendMessage("_Attack",attackData.Name); } animation.CrossFade(attackData.AnimationName); yield return new WaitForSeconds(animation[attackData.AnimationName].length); //If AttackInterrupt = true, means wait for a while, so execute the IdleData if(behavior.AttackInterrupt) { IdleData idleData = this.Unit.IdleDataDict[behavior.IdleDataName]; float interval = Random.Range(behavior.AttackIntervalMin, behavior.AttackIntervalMax); animation.CrossFade(idleData.AnimationName); yield return new WaitForSeconds(interval); animation.Stop(idleData.AnimationName); } else { yield return null; } continue; } //else if can't see target, navigating until CanSeeCurrentTarget = true & within AttackableRange else { MoveData moveData = Unit.MoveDataDict[behavior.MoveDataName]; yield return StartCoroutine(NavigateToTransform(CurrentTarget, moveData, attackData.AttackableRange, 1)); continue; } yield return null; } animation.Stop(attackData.AnimationName); StopBehavior(behavior); }
/// <summary> /// Start Idle. /// </summary> /// <returns></returns> public virtual IEnumerator Start_Idle(AIBehavior behavior) { if(PrintDebugMessage) Debug.Log("Start behavior:" + behavior.Name + " .IdleDataName:" + behavior.IdleDataName); IdleData _IdleData = Unit.IdleDataDict[behavior.IdleDataName]; string IdleAnimationName = _IdleData.AnimationName; float lastScanEndConditionTime = Time.time; while (true) { if (Halt) { animation.Stop(IdleAnimationName); yield return null; continue; } else { animation.CrossFade(IdleAnimationName); //if this behavior's end condition matches, end this behavior if((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if(CheckAlternateBehaviorCondition(behavior)) { if(PrintDebugMessage) { Debug.Log("Idle behavior:" + behavior.Name + " is end."); } break; } } //if the current target is not null and idle data mean to be keep facing at the target, face to the target. if(CurrentTarget != null && _IdleData.KeepFacingTarget) { Vector3 LookAtPosition = new Vector3(CurrentTarget.position.x, transform.position.y, CurrentTarget.position.z); if(_IdleData.SmoothRotate) { RotateData rotateData = Unit.RotateDataDict[_IdleData.RotateDataName]; //Calculate angle distance of forward direction and face to target direction. Vector3 toTargetDir = CurrentTarget.position - transform.position; Vector3 faceDir = transform.forward; if(Vector3.Angle(toTargetDir, faceDir) >= rotateData.AngleDistanceToStartRotate) { Util.RotateToward(transform, LookAtPosition, true, rotateData.RotateAngularSpeed); } } else { transform.LookAt(LookAtPosition); } } yield return null; } } animation.Stop(this.Unit.IdleDataDict[behavior.IdleDataName].AnimationName); StopBehavior(behavior); }
/// <summary> /// Stop behave stopping move to. /// </summary> /// <returns></returns> public virtual IEnumerator Stop_MoveToTransform(AIBehavior behavior) { StopNavigation(); MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; animation.Stop(MoveData.AnimationName); StopCoroutine("Start_MoveToTransform"); yield return null; }
public virtual IEnumerator Start_MoveToCurrentTarget(AIBehavior behavior) { if(Unit.MoveDataDict.ContainsKey(behavior.MoveDataName)==false) { Debug.LogError("Error key:" + behavior.MoveDataName + " at frame:" + Time.frameCount); } MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; float refreshNavigationInterval = 0.3333f; float lastNavigationTime = 0; float lastScanEndConditionTime = Time.time; while (true) { if ((Halt) || (CurrentTarget == null)) { yield return null; continue; } //if this behavior's end condition matches, end this behavior if((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if(CheckAlternateBehaviorCondition(behavior)) { break; } } if((Time.time - lastNavigationTime)>=refreshNavigationInterval) { animation.CrossFade( MoveData.AnimationName); StartNavigation(CurrentTarget, true, MoveData); lastNavigationTime = Time.time; } // float distance = Util.DistanceOfCharacters(gameObject, CurrentTarget.gameObject); // if (distance <= 1) // { // break; // } yield return null; } StopBehavior(behavior); }
public virtual IEnumerator Stop_MoveToWaypoint(AIBehavior behavior) { StopCoroutine("Start_MoveToWaypoint"); behavior.selectedWaypoint = null; yield return null; }
public virtual IEnumerator Start_MoveToWaypoint(AIBehavior behavior) { MoveData MoveData = Unit.MoveDataDict[behavior.MoveDataName]; WayPoint[] wpArray = WayPoint.GetWaypoints(behavior.WaypointNames); WayPoint wp = Util.RandomFromArray<WayPoint>(wpArray); behavior.selectedWaypoint = wp; StartNavigation(behavior.selectedWaypoint.transform, true, MoveData); float lastScanEndConditionTime = Time.time; while (true) { if (Halt) { yield return null; continue; } //if this behavior's end condition matches, end this behavior if((Time.time - lastScanEndConditionTime) >= behavior.AlterBehaviorInterval) { lastScanEndConditionTime = Time.time; if(CheckAlternateBehaviorCondition(behavior)) { break; } } yield return null; } StopBehavior(behavior); }
public override void StopBehavior(AIBehavior behavior) { }