Example #1
0
    /// <summary>
    /// Exits from the actual utilityAction to go to another one
    /// </summary>
    public void ExitTransition(UtilityAction action)
    {
        string last = this.actualState.Name;

        if (ActiveAction != null)
        {
            if (ActiveAction.HasSubmachine)
            {
                this.ActiveAction.subMachine.ResetPerceptionsActiveState();
                new Transition("Max_Utility_Transition", this.ActiveAction.subMachine.actualState, new PushPerception(this),
                               this.GetEntryState(), this, this.ActiveAction.subMachine)
                .FireTransition();
            }
            else
            {
                new Transition("Max_Utility_Transition", this.actualState, new PushPerception(this), action.utilityState, this)
                .FireTransition();
            }
        }
        else
        {
            new Transition("Max_Utility_Transition", this.actualState, new PushPerception(this), action.utilityState, this)
            .FireTransition();
        }

        this.ActiveAction = action;

        //DEBUGGING
        if (DEBUG)
        {
            //EXIT TRANSITION
            Console.WriteLine("[DEBUG] ExitTransition - New active action: " + action.utilityState.Name +
                              ". Active State: " + this.actualState.Name + ". Last active action: " + last);
            Console.WriteLine("-------------------------");

            //UTILITIES
            Console.WriteLine("[DEBUG] Utilities: ");
            foreach (UtilityAction a in this.actions)
            {
                if (a == ActiveAction)
                {
                    Console.Write(a.utilityState.Name + " active action utility " + a.getUtility());
                    if (a.getUtility() * inertia > 1.0f)
                    {
                        Console.WriteLine(" inertia 1.0f");
                    }
                    else
                    {
                        Console.WriteLine(" inertia " + a.getUtility() * inertia);
                    }
                }
                else
                {
                    Console.WriteLine(a.utilityState.Name + " utility " + a.getUtility());
                }
            }
            Console.WriteLine("[DEBUG] FINISHED UTILITIES DEBUG");
            Console.WriteLine("--------------------------------");
        }
    }
Example #2
0
    public IEnumerator Fire(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = false;

        BossController     btr  = ctr as BossController;
        BossHandController hand = btr.SelectOneHand();

        hand.anim.SetBool("Aim", true);
        Coroutine co = StartCoroutine(this.HandFire(btr, hand));

        if (Random.Range(0, 100) < this.boss.doubleAttackProbability)
        {
            BossHandController hand2 = btr.SelectOtherHand(hand);

            hand2.anim.SetBool("Aim", true);
            yield return(btr.Aim(hand2));

            yield return(btr.Fire(hand2));

            yield return(btr.Reset(hand2));
        }

        yield return(co);

        act.isRunning = false;
    }
Example #3
0
    public void RunOptimalAction()
    {
        List <UtilityAction> sortedActions        = utilityActions.OrderByDescending(action => action.Score()).ToList();
        List <UtilityAction> highestScoringSubset = sortedActions.GetRange(0, Mathf.Min(3, sortedActions.Count));

        float z = 0.0f;

        float[] cumScores = new float[highestScoringSubset.Count];
        for (int i = 0; i < cumScores.Length; i++)
        {
            UtilityAction action = highestScoringSubset[i];
            z           += action.Score();
            cumScores[i] = z;
        }

        float x = Random.Range(0, z);

        for (int i = 0; i < cumScores.Length; i++)
        {
            if (x < cumScores[i])
            {
                //This action was randomly chosen out of the best for the AI to take
                highestScoringSubset[i].Run();
                return;
            }
        }

        //We shouldn't reach here unless bucket is empty
    }
Example #4
0
    public override void SetupUtilityAction()
    {
        UtilityConsideration LowHeathCons = new UtilityConsideration(UtilityConsideration.CurveTypes.Polynomial, new Vector2(0, MyAgent.GetComponent <Health>().MaxHealth),
                                                                     GetHealth, -1, 0.6f, 0, 2, 1);

        myUtilityAction = new UtilityAction <GoapGoal>(1, this, LowHeathCons);
    }
        public bool IsCurrentlyRunning(UtilityAction act)
        {
            // if(this.main != null) {
            //  Debug.Log("Check if '" + act.method + "' is running at " + Time.time + "(main -> '" + this.main.method + "')");
            // } else {
            //  Debug.Log("Check if '" + act.method + "' is running at " + Time.time + "(no main)");
            // }

            this.CleanActions();

            if (this.main != null && this.main.method.Equals(act.method))
            {
                return(true);
            }

            foreach (UtilityAction a in this.parallelizables)
            {
                if (a.method.Equals(act.method))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #6
0
    public IEnumerator Death(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = false;

        if (this.isDead)
        {
            yield break;
        }

        BossController     btr   = ctr as BossController;
        BossHandController hand1 = btr.SelectOneHand();
        BossHandController hand2 = btr.SelectOtherHand(hand1);

        this.TryStopCoroutine(ref this.followCoroutine);

        hand1.anim.SetTrigger("Death");
        hand2.anim.SetTrigger("Death");
        Coroutine c1 = StartCoroutine(btr.Reset(hand1));

        yield return(btr.Reset(hand2));

        yield return(c1);

        this.isDead   = true;
        act.isRunning = false;
    }
Example #7
0
    // Choose action with highest utility value
    private void ChooseAction()
    {
        // Don't iterate through list if only one action exists
        if (_AgentActions.Count == 1)
        {
            _CurrentAction = _AgentActions[0];
            return;
        }

        float currentScore = 0;
        float deltaScore   = 0;

        for (int i = 0; i < _AgentActions.Count; i++)
        {
            // Get score of every action in list
            currentScore = _AgentActions[i]._UtilityScore;

            // Check if previous score is bigger than our score we are currently looking at
            // If yes: We skip to the next score until we find a score which is bigger than our current highest score
            // If no: We have our highest score and can finally execute it
            if (deltaScore > currentScore)
            {
                continue;
            }

            // Save the current highest score
            deltaScore = currentScore;

            // Save old action
            _oldAction = _CurrentAction;

            // Assign the best action to our current action to execute
            _CurrentAction = _AgentActions[i];
        }
    }
Example #8
0
    public override void SetupUtilityAction()
    {
        UtilityConsideration nConsideration = new UtilityConsideration();

        nConsideration.GetInput = () => { return(0.1f); };

        myUtilityAction = new UtilityAction <GoapGoal>(1, this, nConsideration);
    }
Example #9
0
    // Update is called once per frame
    public override void UpdateButtons()
    {
        float highestUtility = currentAction != null?currentAction.GetContinueUtility() : -1;

        UtilityAction selectedNextAction = currentAction;

        foreach (UtilityAction potentialAction in options)
        {
            if (currentAction == potentialAction)
            {
                continue;
            }

            float potUtility = potentialAction.GetStartUtility();
            if (potUtility > highestUtility)
            {
                selectedNextAction = potentialAction;
                highestUtility     = potUtility;
            }
        }

        if (selectedNextAction != currentAction)
        {
            if (currentAction != null)
            {
                currentAction.EndAction();
            }
            selectedNextAction.BeginAction();
            currentAction = selectedNextAction;
        }

        lastUtility.Clear();
        if (DebugMode)
        {
            lastUtility.Add("CalulateRetreatSpaceUtility", new UtilityOption()
            {
                value = CalulateRetreatSpaceUtility()
            });
            lastUtility.Add("NormalisedOpponentHorizontalDistance", new UtilityOption()
            {
                value = NormalisedOpponentHorizontalDistance(12)
            });
            lastUtility.Add("CalculateJumpDodgeUtility", new UtilityOption()
            {
                value = CalculateJumpDodgeUtility(DodgeArea.Upper)
            });


            //for (int i = 0; i < options.Count; i++)
            //{
            //    var option = options[i];
            //    lastUtility[option.name] = option;
            //    lastUtility[option.name + "RANK"] = new UtilityOption() { value = i };
            //}
        }

        currentAction.UpdateButtonStatus(out shouldDrop, out shouldFeet);
    }
Example #10
0
    public IEnumerator Wander(MovementController ctr, UtilityAction act)
    {
        RabbitController rtr = ctr as RabbitController;

        yield return(rtr.Wander());

        act.isStoppable = true;
        yield return(rtr.Rest());
    }
Example #11
0
 public override void SetupUtility()
 {
     UtilAction = new UtilityAction <GOAPGoal>(1, this, new UtilityConsideration(), new UtilityConsideration(), new UtilityConsideration());
     UtilAction.Considerations[0].GetInput = SendInventoryCount;
     UtilAction.Considerations[0].p        = 3;
     UtilAction.Considerations[0].k        = 0.2f;
     UtilAction.Considerations[1].GetInput = InventoryAtMax;
     UtilAction.Considerations[2].GetInput = DistanceToTarget;
 }
Example #12
0
    public IEnumerator StandBy(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = true;

        // yield return enemy.WatchOut();
        yield return(new WaitForSeconds(99999f));

        act.isRunning = false;
    }
Example #13
0
    public IEnumerator Patrol(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = true;

        MiteEnemyController mrec = ctr as MiteEnemyController;

        yield return(mrec.Patrol());

        act.isRunning = false;
    }
Example #14
0
    public IEnumerator RunAway(MovementController ctr, UtilityAction act)
    {
        // set 'isStoppable' to true to allow action cancelling.
        act.isStoppable = false;

        // do stuff with ctr...
        yield return(null);

        act.isRunning = false;
    }
Example #15
0
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* ------------------------------------ ACTIONS FUNCTIONS -------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    public override IEnumerator Attack(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = false;

        FlameThrowerEnemyController enemy = ctr as FlameThrowerEnemyController;

        yield return(StartCoroutine(enemy.Fire()));

        act.isRunning = false;
    }
Example #16
0
    public IEnumerator Colour(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = false;

        BossController btr = ctr as BossController;

        yield return(btr.Colour());

        act.isRunning = false;
    }
Example #17
0
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* ------------------------------------ ACTIONS FUNCTIONS -------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    public override IEnumerator Attack(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = false;

        TurrelEnemyController enemy = ctr as TurrelEnemyController;
        Vector3 target = player.position + player.up * 0.5f;

        yield return(StartCoroutine(enemy.ShootAt(target)));

        act.isRunning = false;
    }
Example #18
0
    public override void SetupUtilityAction()
    {
        UtilityConsideration PlayerDetectedCons = new UtilityConsideration();

        PlayerDetectedCons.GetInput = GetConcInput;

        UtilityConsideration PlayerRangeCons = new UtilityConsideration(UtilityConsideration.CurveTypes.Trigonometric, new Vector2(0, MyAgent.GetComponent <GoapAI>().DetectionRadius),
                                                                        GetPlayerDist, 1, 1, 2, 1, 0);

        myUtilityAction = new UtilityAction <GoapGoal>(1, this, PlayerDetectedCons, PlayerRangeCons);
    }
Example #19
0
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* ------------------------------------ ACTIONS FUNCTIONS -------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    /* --------------------------------------------------------------------------------------------*/
    public override IEnumerator Attack(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = false;

        MeleeRangerEnemyController enemy = ctr as MeleeRangerEnemyController;

        enemy.Punch();
        yield return(new WaitForSeconds(0.5f));

        act.isRunning = false;
    }
Example #20
0
    public IEnumerator StandBy(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = true;

        MeleeRangerEnemyController mrec = ctr as MeleeRangerEnemyController;

        mrec.enemy.animator.SetBool("Walk", false);
        yield return(new WaitForSeconds(99999f));

        act.isRunning = false;
    }
 private static string UtilityActionToString(UtilityAction act)
 {
     if (act == null)
     {
         return(string.Empty);
     }
     else
     {
         return(act.method);
     }
 }
Example #22
0
    public IEnumerator Patrol(MovementController ctr, UtilityAction act)
    {
        act.isStoppable = true;

        MeleeRangerEnemyController mrec = ctr as MeleeRangerEnemyController;

        mrec.enemy.animator.SetBool("Walk", true);
        yield return(mrec.Patrol());

        act.isRunning = false;
    }
    public void AddEndListener(string methodName, ActionEvent callback)
    {
        UtilityAction act = this.actions.Find(x => x.method.Equals(methodName));

        if (act == null)
        {
            Debug.LogWarning("WARNING : Could not find action with name '" + methodName + "'.");
            return;
        }

        act.onEnd += callback;
    }
Example #24
0
    public void Cancel(LivingEntity ent)
    {
        ent.StopAllCoroutines();
        this.StopAllCoroutines();

        UtilityAction current = this.controllers.Find(caa => caa.ctr.entity == ent)?.act;

        if (current != null)
        {
            current.isRunning = false;
        }
    }
        private void AddAction(UtilityAction act)
        {
            this.CleanActions();

            if (act.isParallelizable)
            {
                this.parallelizables.Add(act);
            }
            else
            {
                this.main = act;
            }
        }
        public void StartAction(UtilityAction act)
        {
            // Debug.Log("Started '" + act.method + "' at " + Time.time);
            // if action need to run alone
            if (act.isForceAlone)
            {
                // stop all other stoppable running actions
                this.StopAllStoppableAction();
            }

            // start action
            act.Start(this.ctr, this.ctr.entity);
            this.AddAction(act);
        }
Example #27
0
    /// <summary>
    /// Creates a new basic <see cref="UtilityAction"/> in the utility curves engine
    /// </summary>
    /// <param name="name">The name of the utility action</param>
    /// <param name="action">The action the utility action will execute</param>
    /// <param name="factor">The factor that will have the Utility Action</param>
    public UtilityAction CreateUtilityAction(string name, Action action, Factor factor)
    {
        if (!states.ContainsKey(name))
        {
            UtilityAction uAction = new UtilityAction(name, action, factor, this);
            actions.Add(uAction);
            states.Add(name, uAction.utilityState);

            return(uAction);
        }
        else
        {
            throw new DuplicateWaitObjectException(name, "The utility action already exists in the utility engine");
        }
    }
Example #28
0
    /// <summary>
    /// Creates a new specific <see cref="UtilityAction"/> in the utility curves engine that exits to the
    /// <see cref="LeafNode"/> that contains the <see cref="UtilitySystemEngine"/> when the function valueReturned
    /// returns something different than "Running".
    /// </summary>
    /// <param name="name">The name of the utility action</param>
    /// <param name="factor">The factor that will have the Utility Action</param>
    /// <param name="ac">The action that the <see cref="UtilityAction"/> will execute.</param>
    /// <param name="valueReturned">The <see cref="ReturnValues"/> returned to the <see cref="LeafNode"/>. It's used to wait for a
    /// "Succeed" or "Failed".</param>
    /// <param name="behaviourTreeEngine">The <see cref="BehaviourTreeEngine"/> that contains the <see cref="UtilitySystemEngine"/>.</param>
    public UtilityAction CreateUtilityAction(string name, Factor factor, Action ac, Func <ReturnValues> valueReturned, BehaviourTreeEngine behaviourTreeEngine)
    {
        if (!states.ContainsKey(name))
        {
            UtilityAction uAction = new UtilityAction(name, factor, ac, valueReturned, this, behaviourTreeEngine);
            actions.Add(uAction);
            states.Add(name, uAction.utilityState);

            return(uAction);
        }
        else
        {
            throw new DuplicateWaitObjectException(name, "The utility action already exists in the utility engine");
        }
    }
Example #29
0
    /// <summary>
    /// Get the shoot scores of the player unit at index
    /// </summary>
    /// <param name="index">The index of the unit in the shootables List</param>
    /// <returns>The action with its score fleshed out</returns>
    private UtilityAction GetShootScore(int index)
    {
        UtilityAction action = new UtilityAction();

        action.SetScoreToZero();

        // If thisUnit can kill a target, choose that target
        if (shootables[index].GetHealth() <= thisUnit.GetDamage())
        {
            action.AddToScore(200f);
        }
        else
        {
            action.AddToScore(100f - (100f * (shootables[index].GetHealth() / shootables[index].GetMaxHealth())));
        }

        // Snipers are dangerous, so choose that target
        if (shootables[index].GetUnitType() == UnitType.SNIPER)
        {
            action.AddToScore(50f);
        }
        // Otherwise, Tanks are also dangerous, so choose that target
        else if (shootables[index].GetUnitType() == UnitType.TANK)
        {
            action.AddToScore(25f);
        }
        // Lastly, Scouts are dangerous, so choose that target
        else if (shootables[index].GetUnitType() == UnitType.SCOUT)
        {
            action.AddToScore(10f);
        }

        if (thisUnit.GetUnitType() == UnitType.SNIPER)
        {
            Vector3 distance = shootables[index].transform.position - thisUnit.transform.position;

            if (distance.magnitude <= 4)
            {
                action.AddToScore(70f);
            }
            else if (distance.magnitude >= 8)
            {
                action.AddToScore(50f);
            }
        }

        return(action);
    }
Example #30
0
    /// <summary>
    /// Adds a type of <see cref="UtilityAction"/> with a sub-behaviour engine in it and its transition to the specified state
    /// </summary>
    /// <param name="actionName">The name of the action</param>
    /// <param name="factor">The factor that gives the utility value to the action</param>
    /// <param name="subBehaviourEngine">The sub-behaviour tree inside the </param>
    /// <param name="stateTo">The name of the state where the sub-state machine will enter</param>
    public UtilityAction CreateSubBehaviour(string actionName, Factor factor, BehaviourEngine subBehaviourEngine, State stateTo)
    {
        if (!states.ContainsKey(actionName))
        {
            State         state      = new State(actionName, subBehaviourEngine.GetState("Entry_Machine"), stateTo, subBehaviourEngine, this);
            UtilityAction utilAction = new UtilityAction(state, factor, this, subBehaviourEngine);
            states.Add(utilAction.utilityState.Name, utilAction.utilityState);
            actions.Add(utilAction);

            return(utilAction);
        }
        else
        {
            throw new DuplicateWaitObjectException(actionName, "The utility action already exists in the utility engine");
        }
    }