Ejemplo n.º 1
0
        /// <summary>
        /// Main method.
        /// </summary>
        /// <param name="selector"></param>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <exception cref="System.ArgumentNullException">selector or context or provider</exception>
        protected override void FillTreeWithData(Selector selector, ITypeDescriptorContext context, IServiceProvider provider)
        {
            selector.ThrowIfNull(nameof(selector));

            context.ThrowIfNull(nameof(context));

            provider.ThrowIfNull(nameof(provider));

            // Base method, clear the selector
            base.FillTreeWithData(selector, context, provider);

            // Scroll through the pages
            MultiPanel panel = (MultiPanel)context.Instance;
            foreach (MultiPanelPage page in panel.Controls)
            {
                SelectorNode node = new SelectorNode(page.Name, page);
                selector.Nodes.Add(node);

                if (page != panel.SelectedPage)
                    continue;

                selector.SelectedNode = node;
                return;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void FillTreeWithData(Selector selector, ITypeDescriptorContext context, IServiceProvider provider)
        {
            base.FillTreeWithData(selector, context, provider);
            selector.Nodes.Add(new SelectorNode("<None>", null));
            String[] layouts = Directory.GetFiles(this.GetLayoutsDir(), "*.fdl");
            for (Int32 i = 0; i < layouts.Length; i++)
            {
                String label = Path.GetFileNameWithoutExtension(layouts[i]);
                SelectorNode item = new SelectorNode(label, layouts[i]);
                selector.Nodes.Add(item);
            }

        }
        /// <summary>
        /// Main method.
        /// </summary>
        /// <param name="selection"></param>
        /// <param name="context"></param>
        /// <param name="provider"></param>
		protected override void FillTreeWithData(Selector selection, ITypeDescriptorContext context, IServiceProvider provider)
		{
            // Base method, clear the selection
			base.FillTreeWithData(selection, context, provider);	

            // Scroll through the pages
            MultiPanel panel = (MultiPanel)context.Instance;
			foreach (MultiPanelPage page in panel.Controls)
			{
				SelectorNode node = new SelectorNode(page.Name, page);
				selection.Nodes.Add(node);

                if (page == panel.SelectedPage)
                {
                    selection.SelectedNode = node;
                    return;
                }
			}
		}
Ejemplo n.º 4
0
        public void Sequence_Node_Succeds_When_One_Child_Succeeds(int childsCount, int successAt)
        {
            SelectorNode seq = new SelectorNode();

            for (int i = 0; i < childsCount; i++)
            {
                var mock = Substitute.For <BTNode>();
                mock.Update().Returns(i == successAt ? NodeState.Success : NodeState.Failure);
                seq.AddChild(mock);
            }

            for (int i = 0; i <= successAt; i++)
            {
                if (i == successAt)
                {
                    Assert.IsTrue(seq.Update() == NodeState.Success);
                }
                else
                {
                    Assert.IsTrue(seq.Update() == NodeState.Running);
                }
            }
        }
Ejemplo n.º 5
0
        public void Selector_Node_Fails_If_All_Of_Its_Children_Fails(int childsCount)
        {
            SelectorNode seq = new SelectorNode();

            for (int i = 0; i < childsCount; i++)
            {
                var mock = Substitute.For <BTNode>();
                mock.Update().Returns(NodeState.Failure);
                seq.AddChild(mock);
            }

            for (int i = 0; i < childsCount; i++)
            {
                if (i == childsCount - 1)
                {
                    Assert.IsTrue(seq.Update() == NodeState.Failure);
                }
                else
                {
                    Assert.IsTrue(seq.Update() == NodeState.Running);
                }
            }
        }
    public static BehaviorNode InitRootNode(BehaviorTree behaviorTree, AbstractActor unit, GameInstance game)
    {
        IsAttackAvailableForUnitNode attackAvailable0000 = new IsAttackAvailableForUnitNode("attackAvailable0000", behaviorTree, unit);

        FindPlayerTutorialTargetNode findPlayerTutorialTarget0000 = new FindPlayerTutorialTargetNode("findPlayerTutorialTarget0000", behaviorTree, unit);

        ShootTrainingWeaponsAtTargetNode shootTrainingWeaponsAtTarget0000 = new ShootTrainingWeaponsAtTargetNode("shootTrainingWeaponsAtTarget0000", behaviorTree, unit);

        SequenceNode attack_sequence = new SequenceNode("attack_sequence", behaviorTree, unit);

        attack_sequence.AddChild(attackAvailable0000);
        attack_sequence.AddChild(findPlayerTutorialTarget0000);
        attack_sequence.AddChild(shootTrainingWeaponsAtTarget0000);

        BraceNode brace0000 = new BraceNode("brace0000", behaviorTree, unit);

        SelectorNode selector0000 = new SelectorNode("selector0000", behaviorTree, unit);

        selector0000.AddChild(attack_sequence);
        selector0000.AddChild(brace0000);

        return(selector0000);
    }
Ejemplo n.º 7
0
    public static BehaviorNode InitRootNode(BehaviorTree behaviorTree, AbstractActor unit, GameInstance game)
    {
        UnitHasRouteNode unitHasRoute0000 = new UnitHasRouteNode("unitHasRoute0000", behaviorTree, unit);

        LanceHasStartedRouteNode lanceHasStartedRoute0000 = new LanceHasStartedRouteNode("lanceHasStartedRoute0000", behaviorTree, unit);

        LanceStartRouteNode lanceStartRoute0000 = new LanceStartRouteNode("lanceStartRoute0000", behaviorTree, unit);

        SelectorNode selector0000 = new SelectorNode("selector0000", behaviorTree, unit);

        selector0000.AddChild(lanceHasStartedRoute0000);
        selector0000.AddChild(lanceStartRoute0000);

        LanceHasCompletedRouteNode lanceHasCompletedRoute0000 = new LanceHasCompletedRouteNode("lanceHasCompletedRoute0000", behaviorTree, unit);

        InverterNode inverter0000 = new InverterNode("inverter0000", behaviorTree, unit);

        inverter0000.AddChild(lanceHasCompletedRoute0000);

        MoveAlongRouteNode moveAlongRoute0000 = new MoveAlongRouteNode("moveAlongRoute0000", behaviorTree, unit);

        SequenceNode incrementally_patrol = new SequenceNode("incrementally_patrol", behaviorTree, unit);

        incrementally_patrol.AddChild(unitHasRoute0000);
        incrementally_patrol.AddChild(selector0000);
        incrementally_patrol.AddChild(inverter0000);
        incrementally_patrol.AddChild(moveAlongRoute0000);

        BraceNode brace0000 = new BraceNode("brace0000", behaviorTree, unit);

        SelectorNode route_AI_root = new SelectorNode("route_AI_root", behaviorTree, unit);

        route_AI_root.AddChild(incrementally_patrol);
        route_AI_root.AddChild(brace0000);

        return(route_AI_root);
    }
Ejemplo n.º 8
0
    //start with enumerations (simple clear value cases)
    void Start()
    {
        //vul selector node
        //List<INode> nodes = new List<INode>();
        //nodes.Add(new ConditionNode(IsHungry));
        //nodes.Add(new ActionNode(Eat));

        INode selectorNode =
            new SelectorNode(
                new SelectorNode(
                    new ConditionNode(IsHungry),
                    new ActionNode(Eat)),
                new SelectorNode(
                    new SelectorNode(
                        new ConditionNode(IsSleepy),
                        new ActionNode(Sleep))));

        //creeer een condition om de code van IsHungry in op te slaan
        //ConditionNode.Condition hungryCondition = IsHungry;

        //send the code from the method instead of the result of the method | don't use IsHungry(), but use IsHungry
        ConditionNode isHungryCondition = new ConditionNode(IsHungry);
        ConditionNode isSleepyCondition = new ConditionNode(IsSleepy);
    }
Ejemplo n.º 9
0
    private void Awake()
    {
        move = new Vector3(0, 0, 0);
        var tag = GameObject.Find("Tag").GetComponent <Tag>();

        var root = new SelectorNode("/");

        root.Add("/", new DecoratorNode("/IsIt", () => tag.target == this.gameObject.transform));
        root.Add("/IsIt", new ActionNode("/IsIt/RunAfter", () =>
        {
            move = GameObject.Find("Player").transform.position - this.transform.position;
            return(true);
        }));
        root.Add("/", new ActionNode("/RunAway", () =>
        {
            move = this.transform.position - tag.target.position;
            return(true);
        }));

        this.UpdateAsObservable()
        .Subscribe(_ => {
            root.Excute();
        });
    }
    public void Add <TOut>(Expression <Func <T, TOut> > selector)
    {
        var node = new SelectorNode <T, TOut>(selector);

        Add(node);
    }
Ejemplo n.º 11
0
    // Use this for initialization
    void Start()
    {
        //nodes
        rootNode = new SelectorNode();
        //sequensers
        sequencer1 = new SequencerNode();
        sequencer2 = new SequencerNode();
        //selectors
        selector1 = new SelectorNode();
        selector2 = new SelectorNode();
        //repeaters
        repeatUntilFail1 = new RepeatUntilFailNode();
        //behaviours leaf
        leafNodeIdle     = new LeafNodeIdle();
        leafNodeMove     = new LeafNodeMove();
        leafNodeMoveAway = new leafNodeMoveAway();
        //behaviours nodes
        nodeChooseAttack = new NodeChooseAttack();
        //repeater nodes
        repeatSetTimes1 = new RepeatSetTimesNode();
        //check distance decorator
        checkdst = new DecoratorNodeCheckDist();

        bb       = new Blackboard();
        bb.Boss  = GameObject.FindGameObjectWithTag("Boss");
        bb.agent = bb.Boss.GetComponent <NavMeshAgent>();
        bb.closestEnemyCursor  = GameObject.FindGameObjectWithTag("Player");
        bb.movespeed           = bossMoveSpeed;
        bb.aggroRange          = bossAggroRange;
        bb.rotationSpeed       = bossRotationSpeed;
        bb.maxValHealth        = 100f;
        bb.maxValTwoHealth     = 100f;
        bb.currentValHealth    = 100f;
        bb.currentValTwoHealth = 100f;
        bb.fillAmountHealth    = 1f;
        bb.fillAmountTwoHealth = 1f;

        //node inits
        rootNode.InitSelector(bb, "Root");
        nodeChooseAttack.InitAttack(bb, "Attack");
        leafNodeIdle.InitIdle(bb, "Idle");
        leafNodeMove.InitMove(bb, "Move");
        leafNodeMoveAway.Init(bossMoveSpeed, bossRotationSpeed);
        selector1.InitSelector(bb, "Selector");
        sequencer1.InitSequenser(bb, "Sequence");

        checkdst.initDistCheck(bb, "distanceCheck");

        //sequence one children
        rootNode.GetController().AddChild(selector1);
        selector1.GetController().AddChild(leafNodeIdle);
        selector1.GetController().AddChild(sequencer1);
        sequencer1.GetController().AddChild(leafNodeMove);
        sequencer1.GetController().AddChild(checkdst);
        sequencer1.GetController().AddChild(nodeChooseAttack);

        //test for debug
        rootNode.SetCurrentTask(rootNode.GetController().GetChildList().First());
        selector1.SetCurrentTask(selector1.GetController().GetChildList().First());
        sequencer1.SetCurrentTask(sequencer1.GetController().GetChildList().First());
    }
Ejemplo n.º 12
0
 void Init(bool keepState = false)
 {
     testObject = new SelectorNode("some-selector", keepState);
 }
Ejemplo n.º 13
0
        protected override void FillTreeWithData(Selector theSel,
            ITypeDescriptorContext theCtx, IServiceProvider theProvider)
        {
            base.FillTreeWithData(theSel, theCtx, theProvider);	//clear the selection

            MultiPaneControl aCtl = (MultiPaneControl) theCtx.Instance;

            foreach (MultiPanePage aIt in aCtl.Controls)
            {
                SelectorNode aNd = new SelectorNode(aIt.Name, aIt);

                theSel.Nodes.Add(aNd);

                if (aIt == aCtl.SelectedPage)
                    theSel.SelectedNode = aNd;
            }
        }
Ejemplo n.º 14
0
 public void addChild(SelectorNode child)
 {
     child.parent = this;
     children.Add(child);
 }
Ejemplo n.º 15
0
 void Init()
 {
     testObject = new SelectorNode("some-selector");
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Parses the selector string into a sequence of selector nodes.
        /// Returns the leaf node.
        /// </summary>
        public static SelectorNode[] Parse(string fullSelector)
        {
            Regex selectorNodeStringValidator = new Regex(@"^\w+\.\w+|\w+|\.\w+$");

            List<string> nodeStrings = fullSelector.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            List<SelectorNode> nodes = new List<SelectorNode>(nodeStrings.Count);
            SelectorNode node = null;
            for (int i = nodeStrings.Count - 1; i >= 0; --i)
            {
                string nodeString = nodeStrings[i];

                if (nodeString == ">")
                {
                    if (node == null)
                    {
                        // We don't have a leaf node yet. '>' is invalid to discover first.
                        Debug.LogError("Bad syntax in selector \"" + fullSelector + "\".");
                        return null;
                    }
                    else
                    {
                        node.ParentRelationship = SelectorNodeRelationship.Direct;
                        continue;
                    }
                }
                else
                {
                    if (!selectorNodeStringValidator.IsMatch(nodeString))
                    {
                        Debug.LogError("Bad syntax in selector \"" + fullSelector + "\".");
                        return null;
                    }

                    SelectorNode newNode = new SelectorNode();
                    newNode.Parent = node;
                    newNode.ParentRelationship = SelectorNodeRelationship.Indirect; // Indirect until we know otherwise.

                    string[] nodeStringSplit = nodeString.Split('.');

                    if (nodeStringSplit.Length == 1)
                    {
                        if (nodeString.StartsWith("."))
                        {
                            newNode.Class = nodeString;
                        }
                        else
                        {
                            newNode.Type = nodeString;
                        }
                    }
                    else
                    {
                        newNode.Type = nodeStringSplit[0];
                        newNode.Class = nodeStringSplit[1];
                    }

                    nodes.Add(newNode);
                    node = newNode;
                }
            }

            if (nodes.Count == 0)
            {
                return null;
            }
            else
            {
                return nodes.AsEnumerable().Reverse().ToArray();
            }
        }
Ejemplo n.º 17
0
    public static BehaviorNode InitRootNode(BehaviorTree behaviorTree, AbstractActor unit, GameInstance game)
    {
        IsShutDownNode isShutdown0000 = new IsShutDownNode("isShutdown0000", behaviorTree, unit);

        MechStartUpNode mechStartUp0000 = new MechStartUpNode("mechStartUp0000", behaviorTree, unit);

        SequenceNode if_shutdown__restart = new SequenceNode("if_shutdown__restart", behaviorTree, unit);

        if_shutdown__restart.AddChild(isShutdown0000);
        if_shutdown__restart.AddChild(mechStartUp0000);

        IsMovementAvailableForUnitNode movementAvailable0000 = new IsMovementAvailableForUnitNode("movementAvailable0000", behaviorTree, unit);

        IsProneNode isProne0000 = new IsProneNode("isProne0000", behaviorTree, unit);

        StandNode stand0000 = new StandNode("stand0000", behaviorTree, unit);

        SequenceNode if_prone__stand_up = new SequenceNode("if_prone__stand_up", behaviorTree, unit);

        if_prone__stand_up.AddChild(movementAvailable0000);
        if_prone__stand_up.AddChild(isProne0000);
        if_prone__stand_up.AddChild(stand0000);

        IsMovementAvailableForUnitNode movementAvailable0001 = new IsMovementAvailableForUnitNode("movementAvailable0001", behaviorTree, unit);

        HasSensorLockAbilityNode hasSensorLockAbility0000 = new HasSensorLockAbilityNode("hasSensorLockAbility0000", behaviorTree, unit);

        HasSensorLockTargetNode hasSensorLockTarget0000 = new HasSensorLockTargetNode("hasSensorLockTarget0000", behaviorTree, unit);

        SortEnemiesBySensorLockQualityNode sortEnemiesBySensorLockQuality0000 = new SortEnemiesBySensorLockQualityNode("sortEnemiesBySensorLockQuality0000", behaviorTree, unit);

        RecordHighestPriorityEnemyAsSensorLockTargetNode recordHighestPriorityEnemyAsSensorLockTarget0000 = new RecordHighestPriorityEnemyAsSensorLockTargetNode("recordHighestPriorityEnemyAsSensorLockTarget0000", behaviorTree, unit);

        SequenceNode sensor_lock_success = new SequenceNode("sensor_lock_success", behaviorTree, unit);

        sensor_lock_success.AddChild(hasSensorLockAbility0000);
        sensor_lock_success.AddChild(hasSensorLockTarget0000);
        sensor_lock_success.AddChild(sortEnemiesBySensorLockQuality0000);
        sensor_lock_success.AddChild(recordHighestPriorityEnemyAsSensorLockTarget0000);

        ClearSensorLockNode clearSensorLock0000 = new ClearSensorLockNode("clearSensorLock0000", behaviorTree, unit);

        SelectorNode selector0000 = new SelectorNode("selector0000", behaviorTree, unit);

        selector0000.AddChild(sensor_lock_success);
        selector0000.AddChild(clearSensorLock0000);

        SequenceNode evalSensorLock = new SequenceNode("evalSensorLock", behaviorTree, unit);

        evalSensorLock.AddChild(selector0000);

        SuccessDecoratorNode maybe_sensor_lock = new SuccessDecoratorNode("maybe_sensor_lock", behaviorTree, unit);

        maybe_sensor_lock.AddChild(evalSensorLock);

        UnitHasRouteNode unitHasRoute0000 = new UnitHasRouteNode("unitHasRoute0000", behaviorTree, unit);

        LanceHasCompletedRouteNode lanceHasCompletedRoute0000 = new LanceHasCompletedRouteNode("lanceHasCompletedRoute0000", behaviorTree, unit);

        InverterNode inverter0000 = new InverterNode("inverter0000", behaviorTree, unit);

        inverter0000.AddChild(lanceHasCompletedRoute0000);

        LanceHasStartedRouteNode lanceHasStartedRoute0000 = new LanceHasStartedRouteNode("lanceHasStartedRoute0000", behaviorTree, unit);

        LanceStartRouteNode lanceStartRoute0000 = new LanceStartRouteNode("lanceStartRoute0000", behaviorTree, unit);

        SelectorNode selector0001 = new SelectorNode("selector0001", behaviorTree, unit);

        selector0001.AddChild(lanceHasStartedRoute0000);
        selector0001.AddChild(lanceStartRoute0000);

        BlockUntilPathfindingReadyNode blockUntilPathfindingReady0000 = new BlockUntilPathfindingReadyNode("blockUntilPathfindingReady0000", behaviorTree, unit);

        MoveAlongRouteNode moveAlongRoute0000 = new MoveAlongRouteNode("moveAlongRoute0000", behaviorTree, unit);

        SequenceNode move_along_route = new SequenceNode("move_along_route", behaviorTree, unit);

        move_along_route.AddChild(movementAvailable0001);
        move_along_route.AddChild(maybe_sensor_lock);
        move_along_route.AddChild(unitHasRoute0000);
        move_along_route.AddChild(inverter0000);
        move_along_route.AddChild(selector0001);
        move_along_route.AddChild(blockUntilPathfindingReady0000);
        move_along_route.AddChild(moveAlongRoute0000);

        HasSensorLockAbilityNode hasSensorLockAbility0001 = new HasSensorLockAbilityNode("hasSensorLockAbility0001", behaviorTree, unit);

        HasRecordedSensorLockTargetNode hasRecordedSensorLockTarget0000 = new HasRecordedSensorLockTargetNode("hasRecordedSensorLockTarget0000", behaviorTree, unit);

        SetMoodNode setMood0000 = new SetMoodNode("setMood0000", behaviorTree, unit, AIMood.Aggressive);

        SensorLockRecordedSensorLockTargetNode sensorLockRecordedSensorLockTarget0000 = new SensorLockRecordedSensorLockTargetNode("sensorLockRecordedSensorLockTarget0000", behaviorTree, unit);

        SequenceNode choseToSensorLock = new SequenceNode("choseToSensorLock", behaviorTree, unit);

        choseToSensorLock.AddChild(hasSensorLockAbility0001);
        choseToSensorLock.AddChild(hasRecordedSensorLockTarget0000);
        choseToSensorLock.AddChild(setMood0000);
        choseToSensorLock.AddChild(sensorLockRecordedSensorLockTarget0000);

        LanceDetectsEnemiesNode lanceDetectsEnemies0000 = new LanceDetectsEnemiesNode("lanceDetectsEnemies0000", behaviorTree, unit);

        FindDetectedEnemiesNode findDetectedEnemies0000 = new FindDetectedEnemiesNode("findDetectedEnemies0000", behaviorTree, unit);

        IsAttackAvailableForUnitNode attackAvailable0000 = new IsAttackAvailableForUnitNode("attackAvailable0000", behaviorTree, unit);

        SortEnemiesByThreatNode sortEnemiesByThreat0000 = new SortEnemiesByThreatNode("sortEnemiesByThreat0000", behaviorTree, unit);

        UseNormalToHitThreshold useNormalToHitThreshold0000 = new UseNormalToHitThreshold("useNormalToHitThreshold0000", behaviorTree, unit);

        WasTargetedRecentlyNode wasTargetedRecently0000 = new WasTargetedRecentlyNode("wasTargetedRecently0000", behaviorTree, unit);

        InverterNode inverter0001 = new InverterNode("inverter0001", behaviorTree, unit);

        inverter0001.AddChild(wasTargetedRecently0000);

        RandomPercentageLessThanBVNode randomPercentageLessThanBV0000 = new RandomPercentageLessThanBVNode("randomPercentageLessThanBV0000", behaviorTree, unit, BehaviorVariableName.Float_PriorityAttackPercentage);

        SortEnemiesByPriorityListNode sortEnemiesByPriorityList0000 = new SortEnemiesByPriorityListNode("sortEnemiesByPriorityList0000", behaviorTree, unit);

        SequenceNode sequence0000 = new SequenceNode("sequence0000", behaviorTree, unit);

        sequence0000.AddChild(inverter0001);
        sequence0000.AddChild(randomPercentageLessThanBV0000);
        sequence0000.AddChild(sortEnemiesByPriorityList0000);

        MaybeFilterOutPriorityTargetsNode maybeFilterOutPriorityTargets0000 = new MaybeFilterOutPriorityTargetsNode("maybeFilterOutPriorityTargets0000", behaviorTree, unit);

        FilterKeepingRecentAttackersNode filterKeepingRecentAttackers0000 = new FilterKeepingRecentAttackersNode("filterKeepingRecentAttackers0000", behaviorTree, unit);

        SucceedNode succeed0000 = new SucceedNode("succeed0000", behaviorTree, unit);

        SelectorNode priorityAttack = new SelectorNode("priorityAttack", behaviorTree, unit);

        priorityAttack.AddChild(sequence0000);
        priorityAttack.AddChild(maybeFilterOutPriorityTargets0000);
        priorityAttack.AddChild(filterKeepingRecentAttackers0000);
        priorityAttack.AddChild(succeed0000);

        ShootAtHighestPriorityEnemyNode shootAtHighestPriorityEnemy0000 = new ShootAtHighestPriorityEnemyNode("shootAtHighestPriorityEnemy0000", behaviorTree, unit);

        SequenceNode opportunity_fire = new SequenceNode("opportunity_fire", behaviorTree, unit);

        opportunity_fire.AddChild(lanceDetectsEnemies0000);
        opportunity_fire.AddChild(findDetectedEnemies0000);
        opportunity_fire.AddChild(attackAvailable0000);
        opportunity_fire.AddChild(sortEnemiesByThreat0000);
        opportunity_fire.AddChild(useNormalToHitThreshold0000);
        opportunity_fire.AddChild(priorityAttack);
        opportunity_fire.AddChild(shootAtHighestPriorityEnemy0000);

        BraceNode brace0000 = new BraceNode("brace0000", behaviorTree, unit);

        SelectorNode patrol_and_shoot_AI_root = new SelectorNode("patrol_and_shoot_AI_root", behaviorTree, unit);

        patrol_and_shoot_AI_root.AddChild(if_shutdown__restart);
        patrol_and_shoot_AI_root.AddChild(if_prone__stand_up);
        patrol_and_shoot_AI_root.AddChild(move_along_route);
        patrol_and_shoot_AI_root.AddChild(choseToSensorLock);
        patrol_and_shoot_AI_root.AddChild(opportunity_fire);
        patrol_and_shoot_AI_root.AddChild(brace0000);

        return(patrol_and_shoot_AI_root);
    }
Ejemplo n.º 18
0
        protected override SelectorNode CreateBehaviour()
        {
            //create the dig nodes
            CanDigNode               canDigNode         = new CanDigNode(this);
            HealthLessThanNode       healthCheckNode    = new HealthLessThanNode(this, 0.6f);
            AnimatorNode             digAnimationNode   = new AnimatorNode(this, m_AnimatorRef, "IsDigging", ref m_DigAnimationLink);
            ToggleParticleSystemNode toggleParticleNode = new ToggleParticleSystemNode(this, DigParticleSystem);

            DelegateNode.Delegate toggleTriggerFunc = SetColliderTrigger;
            DelegateNode          toggleTriggerNode = new DelegateNode(this, toggleTriggerFunc, true);

            DelegateNode.Delegate toggleColliderFunc = ToggleCollider;
            DelegateNode          toggleColliderNode = new DelegateNode(this, toggleColliderFunc);

            ToggleNavMeshAgentNode toggleAgentNode = new ToggleNavMeshAgentNode(this);
            DelayNode delayNode = new DelayNode(this, 2.0f);
            //TODO: COMMENT THIS SECTION AND ADD STRING
            PlaySoundNode digSFX       = new PlaySoundNode(this, "NergDig");
            LerpNode      lerpDownNode = new LerpNode(this, Vector3.down, 1.0f, 2.0f, 10.0f);

            DelegateNode.Delegate rotateFunc = RotateVertical;
            DelegateNode          rotateNode = new DelegateNode(this, rotateFunc);

            TeleportToTargetOffsetNode teleportNode     = new TeleportToTargetOffsetNode(this, new Vector3(0.0f, -5.0f, 0.0f));
            LerpToTargetNode           lerpToTargetNode = new LerpToTargetNode(this, 0.5f, 1.0f, 10.0f);
            AnimatorNode        biteAnimationNode       = new AnimatorNode(this, m_AnimatorRef, "IsBiting", ref m_BiteAnimationLink);
            RunUntillTargetNull targetNullNode          = new RunUntillTargetNull(this);

            //create the dig sequence
            SequenceNode digSequence = new SequenceNode(this, "DigSequence",
                                                        healthCheckNode,
                                                        canDigNode,
                                                        toggleParticleNode,
                                                        toggleTriggerNode,
                                                        toggleColliderNode,
                                                        toggleAgentNode,
                                                        delayNode,
                                                        digSFX,
                                                        lerpDownNode,
                                                        toggleParticleNode,
                                                        rotateNode,
                                                        teleportNode,
                                                        toggleColliderNode,
                                                        toggleParticleNode,
                                                        lerpToTargetNode,
                                                        digSFX,
                                                        delayNode,
                                                        toggleParticleNode,
                                                        targetNullNode
                                                        );

            //create the targeting nodes
            TargetingSightNode     sightNode  = new TargetingSightNode(this, 1);
            TargetingLowHealthNode lowHealth  = new TargetingLowHealthNode(this, 3);
            CalculateTargetNode    calcTarget = new CalculateTargetNode(this);

            //assign the targeting sequence
            SequenceNode targetingSequ = new SequenceNode(this, "TargetingSequence", sightNode, lowHealth, calcTarget);

            //create the spit nodes
            CooldownNode spitCooldownNode = new CooldownNode(this, 1.0f);
            //AnimatorNode spitAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsSpitting", ref m_SpitAnimationLink);
            ShootProjectileNode projectileNode = new ShootProjectileNode(this, 1, ProjectilePrefab, ProjectileSpawnLoc, "MasterNergProjectile", 10);
            //SFX for the sound of the nerg spitting
            PlaySoundNode spitSound = new PlaySoundNode(this, "NergSpit");


            //create the movement nodes
            CooldownNode movementCooldownNode = new CooldownNode(this, 3.0f);
            //BackAwayNode backAwayNode = new BackAwayNode(this, false, 1.0f);
            SideStepNode             sideStepNode        = new SideStepNode(this, false, 2.0f);
            PredictiveAvoidanceNode  predictMovementNode = new PredictiveAvoidanceNode(this, false, true, 2.0f, 5.0f);
            MovementOptionRandomNode movementNodes       = new MovementOptionRandomNode(this, sideStepNode, predictMovementNode);

            //SFX for the sound of the nerg moving backward
            //TODO: COMMENT THIS SECTION AND ADD STRING
            //PlaySoundNode crawlingSFX = new PlaySoundNode(this,);

            //create the spit sequence
            SequenceNode spitSequence = new SequenceNode(this, "SpitSequence", spitCooldownNode, projectileNode, spitSound, movementCooldownNode, movementNodes /*, crawlingSFX*/);

            //assign the attack selector
            SelectorNode attackSelector = new SelectorNode(this, "AttackSelector", digSequence, spitSequence);

            //create the attack sequence
            SequenceNode attackSequence = new SequenceNode(this, "AttackTargetSequence", targetingSequ, attackSelector);

            //create utility selector
            SelectorNode utilitySelector = new SelectorNode(this, "UtilitySelector", attackSequence);

            return(utilitySelector);
        }
Ejemplo n.º 19
0
        protected override SelectorNode CreateBehaviour()
        {
            //Create melee attack nodes

            //Create ground slam nodes
            CooldownNode   groundSlamCooldownNode       = new CooldownNode(this, GroundSlamCooldownTime);
            AnimatorNode   groundSlamStartAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsGroundSlamStarting", ref m_GroundSlamStartLink);
            GroundSlamNode groundSlamNode = new GroundSlamNode(this, FallingRockPrefab, PunchHitBox.transform);

            //TODO: COMMENT THIS SECTION AND ADD STRING
            PlaySoundNode slamSFX = new PlaySoundNode(this, "GolemGroundSlamImpact");
            AnimatorNode  groundSlamRecoveryAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsGroundSlamRecovering", ref m_GroundSlamRecoveryLink);

            ToggleParticleSystemNode toggleGroundSlamPartclesNode = new ToggleParticleSystemNode(this, SlamParticleSystem);

            //Create ground slam sequence
            SequenceNode groundSlamSequence = new SequenceNode(this, "GroundSlamSequence", groundSlamCooldownNode, groundSlamStartAnimationNode, groundSlamNode, toggleGroundSlamPartclesNode, slamSFX, groundSlamRecoveryAnimationNode);

            //Create punch nodes
            CheckDistanceToTargetNode punchDistanceNode = new CheckDistanceToTargetNode(this, 5.0f);

            ToggleMeleeColliderNode togglePunchNode = new ToggleMeleeColliderNode(this, PunchHitBox, 15);

            LookAtTargetNode lookAtTargetNode   = new LookAtTargetNode(this);
            AnimatorNode     punchAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsPunching", ref m_PunchLink);
            //TODO: COMMENT THIS SECTION AND ADD STRING
            PlaySoundNode punchSFX = new PlaySoundNode(this, "GolemPunchImpact");
            //Create punch sequence
            SequenceNode punchSequence = new SequenceNode(this, "PunchSequence", punchDistanceNode, togglePunchNode, lookAtTargetNode, punchSFX, punchAnimationNode, togglePunchNode);

            //Create melee attack selector in order: GroundSlam, Punch
            SelectorNode meleeAttackSelector = new SelectorNode(this, "MeleeAttackSelector");

            meleeAttackSelector.AddChildren(groundSlamSequence, punchSequence);

            //Create ranged attack nodes

            //Create rock throw nodes
            CooldownNode rockThrowCooldownNode       = new CooldownNode(this, 10.0f);
            AnimatorNode rockThrowStartAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsRockThrowStarting", ref m_RockThrowStartLink);
            //TODO: COMMENT THIS SECTION AND ADD STRING
            PlaySoundNode rockThrowSFX = new PlaySoundNode(this, "GolemRockThrow");

            DelegateNode.Delegate setRockMeshFunc     = SetRockMesh;
            DelegateNode          setRockMeshTrueNode = new DelegateNode(this, setRockMeshFunc, true);

            AnimatorNode  rockThrowingAnimationNode      = new AnimatorNode(this, m_AnimatorRef, "IsRockThrowing", ref m_RockThrowingLink);
            DelegateNode  setRockMeshFalseNode           = new DelegateNode(this, setRockMeshFunc, false);
            RockThrowNode rockThrowNode                  = new RockThrowNode(this, RockThrowPrefab, FireLocation, RockThrowDamage);
            AnimatorNode  rockThrowRecoveryAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsRockThrowRecovering", ref m_RockThrowRecoveryLink);

            //Create rock throw sequence
            SequenceNode rockThrowSequence = new SequenceNode(this, "RockThrowSequence", rockThrowCooldownNode,
                                                              rockThrowStartAnimationNode,
                                                              setRockMeshTrueNode,
                                                              rockThrowingAnimationNode,
                                                              setRockMeshFalseNode,
                                                              rockThrowNode,
                                                              rockThrowSFX,
                                                              rockThrowRecoveryAnimationNode
                                                              );

            //Create ground spike nodes
            CooldownNode     groundSpikesCooldownNode       = new CooldownNode(this, 10.0f);
            AnimatorNode     groundSpikesStartAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsGroundSpikeStarting", ref m_GroundSpikesStartLink);
            GroundSpikesNode groundSpikesNode = new GroundSpikesNode(this, SpikePrefab, SpikesMovementTime);
            AnimatorNode     groundSpikesRecoveryAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsGroundSpikesRecovering", ref m_GroundSpikesRecoveryLink);

            //Create ground spike sequence
            SequenceNode groundSpikesSequence = new SequenceNode(this, "GroundSpikesSequence", groundSpikesCooldownNode, groundSpikesStartAnimationNode, groundSpikesNode, groundSpikesRecoveryAnimationNode);

            //Create ranged attack selector in order: RockThrow, GroundSpikes
            SelectorNode rangedAttackSelector = new SelectorNode(this, "RangedAttackSelector");

            rangedAttackSelector.AddChildren(rockThrowSequence, groundSpikesSequence);

            //Create targeting nodes
            TargetingAfflicted         targetingAfflictedNode     = new TargetingAfflicted(this, 8, Status.Stun);
            TargetingDistanceNode      targetingDistanceNode      = new TargetingDistanceNode(this, 1);
            TargetingHighHealthNode    targetingHighHealthNode    = new TargetingHighHealthNode(this, 1);
            TargetingHighestDamageNode targetingHighestDamageNode = new TargetingHighestDamageNode(this, 1);
            TargetingCharacterType     targetingCharacterType     = new TargetingCharacterType(this, 1, WeaponType.RANGED);
            CalculateTargetNode        calculateTargetNode        = new CalculateTargetNode(this);

            //Create the targeting sequence and attach nodes
            SequenceNode targetingSequence = new SequenceNode(this, "TargetingSequence");

            targetingSequence.AddChildren(targetingAfflictedNode,
                                          targetingDistanceNode,
                                          targetingHighHealthNode,
                                          targetingHighestDamageNode,
                                          targetingCharacterType,
                                          calculateTargetNode);

            //Create approach node
            ApproachNode approachNode = new ApproachNode(this);

            //Create Abilities/Melee/Ranged/Approach Selector
            SelectorNode actionSelector = new SelectorNode(this, "ActionSelector");

            actionSelector.AddChildren(meleeAttackSelector, rangedAttackSelector, approachNode);

            //Create Target->Action sequence
            SequenceNode getTargetAndUseAbilitySequence = new SequenceNode(this, "GetTargetAndUseAbilitySequence");

            getTargetAndUseAbilitySequence.AddChildren(targetingSequence, actionSelector);

            //Create the utility selector with the previous sequence and approach node
            SelectorNode utilitySelector = new SelectorNode(this, "UtilitySelector");

            utilitySelector.AddChildren(getTargetAndUseAbilitySequence);

            return(utilitySelector);
        }
Ejemplo n.º 20
0
    protected void DefineNode()
    {
        // RunningFromEnemy
        n_GetClosestEnemy             = new LeafNode(GetClosestEnemy_node);
        n_IsPlayerPowerHigerThanEnemy = new LeafNode(IsPlayerPowerHigerThanEnemy);
        n_MeetWithDestination         = new LeafNode(MeetWithDestination);
        n_BackToTowerAction           = new LeafNode(BackToTowerAction);

        n_IsPlayerPowerLowerThanEnemy = new InverterNode(n_IsPlayerPowerHigerThanEnemy);

        n_BackToTower = new SelectorNode(new List <Node>
        {
            n_MeetWithDestination,
            n_BackToTowerAction
        });

        n_RunningFromEnemy = new SequenceNode(new List <Node>
        {
            n_GetClosestEnemy,
            n_IsPlayerPowerLowerThanEnemy,
            n_BackToTower
        });
        //end running

        // goto nearest checkpoint

        n_IsAlreadyHaveDestination      = new LeafNode(IsAlreadyHaveDestination);
        n_GetNearestCheckPoint          = new LeafNode(GetNearestCheckPoint);
        n_MeetWithDestinationCheckPoint = new LeafNode(MeetWithDestination);
        n_GotoCheckPointAction          = new LeafNode(GotoCheckPointAction);

        n_SetDestinationCheckpoint = new SelectorNode(new List <Node>
        {
            n_IsAlreadyHaveDestination,
            n_GetNearestCheckPoint
        });
        n_GotoCheckPoint = new SelectorNode(new List <Node>
        {
            n_MeetWithDestinationCheckPoint,
            n_GotoCheckPointAction
        });

        n_GotoNearestCheckpoint = new SequenceNode(new List <Node>
        {
            n_SetDestinationCheckpoint,
            n_GotoCheckPoint
        });

        //end nearest

        //Back to tower if power is critical
        n_CheckIfPowerisCritical = new LeafNode(CheckIfPowerIsCritical);

        n_BackToTowerifPowerIsCritical = new SequenceNode(new List <Node>()
        {
            n_CheckIfPowerisCritical,
            n_BackToTower
        });
        //end back

        n_root = new SelectorNode(new List <Node>
        {
            n_BackToTowerifPowerIsCritical,
            n_RunningFromEnemy,
            n_GotoNearestCheckpoint
        });
    }
Ejemplo n.º 21
0
    Node InitializeBehaviourTree()
    {
        #region IDLE BEHAVIOURS
        // Selector to decide if the guard should selector a new waypoint on continue on his current path
        SelectorNode movement = new SelectorNode("Movement Selector",
                                                 new PickLocation(ref guardBlackboard, ref navAgent, gameObject),
                                                 new Move(ref guardBlackboard, ref navAgent));

        // Checks the guards state, if idle, set speed and perform movement selector
        SequenceNode idlePatrol = new SequenceNode("Idle Patrol",
                                                   new CheckState(ref guardBlackboard, Guardblackboard.GuardState.idle, ref navAgent),
                                                   new SetSpeed(IDLE_SPEED, ref navAgent),
                                                   movement);

        // Checks the guards state, if investigating, set speed and patrol waypoints at increased speed
        SequenceNode alertedPatrol = new SequenceNode("Alerted Patrol",
                                                      new CheckState(ref guardBlackboard, Guardblackboard.GuardState.investigate, ref navAgent),
                                                      new SetSpeed(ALERTED_SPEED, ref navAgent),
                                                      movement);

        // Checks state, if idle or conversing then condition is passed
        SelectorNode conversationStateCheck = new SelectorNode("Conversation State Check",
                                                               new CheckState(ref guardBlackboard, Guardblackboard.GuardState.idle, ref navAgent),
                                                               new CheckState(ref guardBlackboard, Guardblackboard.GuardState.converse, ref navAgent));

        // If conversation check is passed try and perform conversation branch
        SequenceNode converse = new SequenceNode("Conversation Sequence",
                                                 conversationStateCheck,
                                                 new CanConverse(ref guardBlackboard),
                                                 new IsFriendlyNear(ref guardBlackboard, ref globalBlackboard),
                                                 //new CanFriendlyConverse(ref guardBlackboard),
                                                 //new LookAt(ref guardBlackboard),
                                                 new WaitForTime(ref guardBlackboard, 4f, ref navAgent));

        SelectorNode patrol = new SelectorNode("Patrol Selector",
                                               alertedPatrol,
                                               idlePatrol);

        SelectorNode idle = new SelectorNode("Idle Selector",
                                             converse,
                                             patrol);
        #endregion

        #region COMBAT BEHAVIOURS
        // Movement is a sequence rather than selector like idle as player could be moving
        SequenceNode combatMovement = new SequenceNode("Combat Movement",
                                                       new CombatPickLocation(ref guardBlackboard, ref navAgent, ref globalBlackboard),
                                                       new Move(ref guardBlackboard, ref navAgent));

        SequenceNode shootPlayer = new SequenceNode("Shoot Player",
                                                    new CheckRange(ref guardBlackboard, 3f),
                                                    new ShootPlayer(ref globalBlackboard));

        SelectorNode shootOrMove = new SelectorNode("Shoot or Move",
                                                    shootPlayer,
                                                    combatMovement);

        // If the player has been sighted by another guard or by the CCTV move to the spoted location and perform a "wander"
        // type steering behaviour
        SequenceNode playerSighted = new SequenceNode("Player Sighted",
                                                      new CheckState(ref guardBlackboard, Guardblackboard.GuardState.alerted, ref navAgent),
                                                      new SetSpeed(ALERTED_SPEED, ref navAgent),
                                                      new SetSearchZone(ref guardBlackboard, ref globalBlackboard, ref navAgent, 10));

        // If the player is in sight of this guard, set speed and close them down
        SequenceNode playerInSight = new SequenceNode("Player In Sight",
                                                      new CheckState(ref guardBlackboard, Guardblackboard.GuardState.combat, ref navAgent),
                                                      new SetSpeed(COMBAT_SPEED, ref navAgent),
                                                      shootOrMove);

        SelectorNode combat = new SelectorNode("Combat Selector",
                                               playerInSight,
                                               playerSighted);
        #endregion

        SelectorNode root = new SelectorNode("root",
                                             idle,
                                             combat);

        return(root);
    }
Ejemplo n.º 22
0
    void Start()
    {
        _behaviorTreeController = new BehaviorTreeController();

        // rootとなるSequencer
        SequencerNode rootNode = new SequencerNode();

        rootNode.name = "rootノード";

        // 出発
        ActionNode departure = new ActionNode();

        departure.name = "出発する";
        departure.SetRunningFunc(() => {
            Debug.LogError("出発");
            return(NodeStatus.SUCCESS);
        });

        // HP確認のDecorator
        DecoratorNode confirmationHp = new DecoratorNode();

        confirmationHp.name = "HP確認するのDecorator";
        confirmationHp.SetConditionFunc(() => {
            return(_myHp >= 100 ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // 敵に寄る
        ActionNode enemyApproach = new ActionNode();

        enemyApproach.name = "敵に寄るアクションノード";
        enemyApproach.SetRunningFunc(() => {
            Debug.LogError("敵に寄る");
            return(NodeStatus.SUCCESS);
        });

        // HP確認のDecoratorの子供登録
        confirmationHp.AddChild(enemyApproach);

        // 友達2人を呼ぶParallelNode
        ParallelNode callFriendAB = new ParallelNode();

        callFriendAB.name = "友達2人を呼ぶParallelNode";

        // 友達A
        ActionNode friendA = new ActionNode();

        friendA.name = "友達Aを呼ぶ";
        friendA.SetRunningFunc(() => {
            Debug.LogError("友達A");
            return(NodeStatus.SUCCESS);
        });

        // 友達B
        ActionNode friendB = new ActionNode();

        friendB.name = "友達Bを呼ぶ";
        friendB.SetRunningFunc(() => {
            Debug.LogError("友達B");
            return(NodeStatus.SUCCESS);
        });

        // 友達2人を呼ぶParallelNodeの子供登録
        callFriendAB.AddChild(friendA);
        callFriendAB.AddChild(friendB);

        // スキルを繰り返し行うRepeaterNode
        RepeaterNode skillRepeater = new RepeaterNode();

        skillRepeater.name = "スキルを繰り返し行うRepeaterNode";

        // スキルを選択するSelector
        SelectorNode selectSkill = new SelectorNode();

        selectSkill.name = "スキルを選択するSelector";

        // スキルAの発動を確認するDecorator
        DecoratorNode triggerSkillA = new DecoratorNode();

        triggerSkillA.name = "スキルAの発動を確認するDecorator";
        triggerSkillA.SetConditionFunc(() => {
            int probability = Mathf.Clamp(probabilitySkillA, 0, 100);
            int random      = Random.Range(0, 100);
            return(probability > random ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // スキルA
        ActionNode skillA = new ActionNode();

        skillA.name = "skillA";
        skillA.SetRunningFunc(() => {
            Debug.LogError("skillA");
            _enemyHp -= 50;
            return(NodeStatus.SUCCESS);
        });

        // スキルAの発動を確認するDecoratorの子供登録
        triggerSkillA.AddChild(skillA);


        // スキルB
        ActionNode skillB = new ActionNode();

        skillB.name = "skillB";
        skillB.SetRunningFunc(() => {
            Debug.LogError("skillB");
            _enemyHp -= 60;
            return(NodeStatus.SUCCESS);
        });

        // スキルを選択するSelectorの子供登録
        selectSkill.AddChild(triggerSkillA);
        selectSkill.AddChild(skillB);

        // スキルを繰り返し行うRepeaterNodeの子供登録
        skillRepeater._repeatNum = 2;
        skillRepeater.AddChild(selectSkill);

        // 敵の生存を確認するSelector
        SelectorNode enemySurvial = new SelectorNode();

        enemySurvial.name = "敵の生存を確認するSelector";

        // 敵が死んでいるか確認するDecorator
        DecoratorNode enemyDied = new DecoratorNode();

        enemyDied.name = "敵が死んでいるか確認するDecorator";
        enemyDied.SetConditionFunc(() => {
            return(_enemyHp <= 0 ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // 敵が死んでいる
        ActionNode died = new ActionNode();

        died.name = "敵が死んでいる";
        died.SetRunningFunc(() => {
            Debug.LogError("End1");
            Debug.LogError("EnemyHp : " + _enemyHp);
            return(NodeStatus.SUCCESS);
        });

        // 敵が死んでいるか確認するDecoratorの子供登録
        enemyDied.AddChild(died);

        // 敵が生きているか確認するDecorator
        DecoratorNode enemyAlive = new DecoratorNode();

        enemyAlive.name = "敵が生きているか確認するDecorator";
        enemyAlive.SetConditionFunc(() => {
            return(_enemyHp > 0 ? NodeStatus.SUCCESS : NodeStatus.FAILURE);
        });

        // 敵が生きている
        ActionNode alive = new ActionNode();

        alive.name = "敵が生きている";
        alive.SetRunningFunc(() => {
            Debug.LogError("End2");
            Debug.LogError("EnemyHp : " + _enemyHp);
            return(NodeStatus.SUCCESS);
        });

        // 敵が生きているか確認するDecoratorの子供登録
        enemyAlive.AddChild(alive);

        // 敵の生存を確認するSelectorの子供登録
        enemySurvial.AddChild(enemyDied);
        enemySurvial.AddChild(enemyAlive);


        // rootノードの子供登録
        rootNode.AddChild(departure);
        rootNode.AddChild(confirmationHp);
        rootNode.AddChild(callFriendAB);
        rootNode.AddChild(skillRepeater);
        rootNode.AddChild(enemySurvial);

        // ツリー実行
        _behaviorTreeController.Initialize(rootNode);
        _behaviorTreeController.OnStart();
    }
Ejemplo n.º 23
0
    // Use this for initialization
    void Start()
    {
        // -- ROOT AND ITS CHILDREN --
        // Root node selector
        m_AI = new SelectorNode();
        //m_AI = gameObject.AddComponent<SelectorNode>();

        // 1st node of Root
        Condition     whistleCondition = new Condition(Conditions.hasWhistled);
        ConditionNode whistle          = new ConditionNode(whistleCondition, this);
        //ConditionNode whistle = gameObject.AddComponent<ConditionNode>();

        // 2nd node of Root
        Condition     inSphereCondition = new Condition(Conditions.inSphere);
        ConditionNode inSphere          = new ConditionNode(inSphereCondition, this);

        // 3rd node of Root
        StochasticNode runFaster = new StochasticNode();

        // Adding children to Root
        m_AI.AddNode(whistle);
        m_AI.AddNode(inSphere);
        m_AI.AddNode(runFaster);

        // -- CHILDREN OF WHISTLE CONDITION (1ST CHILD OF ROOT) --
        Action     approachAction = new Action(Actions.ApproachPlayer);
        ActionNode approach       = new ActionNode(approachAction, this);

        whistle.AddNode(approach);

        // -- CHILDREN OF IN-SPHERE CONDITION (2ND CHILD OF ROOT) --
        Condition     interactingCondition = new Condition(Conditions.interacting);
        ConditionNode interacting          = new ConditionNode(interactingCondition, this);

        inSphere.AddNode(interacting);

        // -- CHILDREN OF RUN-FASTER CONDITION (3RD CHILD OF ROOT) --
        SequenceNode runAhead = new SequenceNode();
        SequenceNode runWith  = new SequenceNode();

        runFaster.AddNode(runAhead);
        runFaster.AddNode(runWith);

        // -- CHILDREN OF INTERACTING CONDITION NODE (CHILD OF IN-SPHERE CONDITION) --
        SequenceNode sitThenHunt = new SequenceNode();
        SequenceNode idle        = new SequenceNode();

        interacting.AddNode(sitThenHunt);
        interacting.AddNode(idle);

        // -- CHILDREN OF SIT-THEN-HUNT SEQUENCE (CHILD OF SIT-THEN-HUNT SEQUENCE) --
        Action       sitAction    = new Action(Actions.Sit);
        ActionNode   sit          = new ActionNode(sitAction, this);
        SequenceNode huntSequence = new SequenceNode();

        sitThenHunt.AddNode(sit);
        sitThenHunt.AddNode(huntSequence);

        // -- CHILDREN OF IDLE SEQUENCE (CHILD OF IDLE SEQUENCE) --
        Action        sniffAction         = new Action(Actions.Sniff);
        ActionNode    randomSpot          = new ActionNode(sniffAction, this);
        Condition     tenMinutesCondition = new Condition(Conditions.tenMinutes);
        ConditionNode tenMinutes          = new ConditionNode(tenMinutesCondition, this);

        idle.AddNode(randomSpot);
        idle.AddNode(tenMinutes); // joint child

        // -- CHILDREN OF RUN-AHEAD SEQUENCE (CHILD OF RUN-FASTER CONDITION) --
        Action     runFastAction = new Action(Actions.RunFast);
        ActionNode runFast       = new ActionNode(runFastAction, this);
        Action     waitAction    = new Action(Actions.Wait);
        ActionNode turnAndWait   = new ActionNode(waitAction, this);

        runAhead.AddNode(runFast);
        runAhead.AddNode(tenMinutes); // joint child
        tenMinutes.AddNode(huntSequence);
        runAhead.AddNode(turnAndWait);

        // -- CHILDREN OF RUN-WITH SEQUENCE (CHILD OF RUN-FASTER CONDITION) --
        Action     runWithAction = new Action(Actions.RunWith);
        ActionNode runNear       = new ActionNode(runWithAction, this);

        runWith.AddNode(runNear);

        // -- CHILDREN OF HUNT SEQUENCE (CHILD OF SIT-THEN-HUNT SEQUENCE AND TEN-MINUTES CONDITION) --
        Action     dissapearAction = new Action(Actions.Dissapear);
        ActionNode dissapear       = new ActionNode(dissapearAction, this);
        Action     huntedAction    = new Action(Actions.Hunted);
        ActionNode hunted          = new ActionNode(huntedAction, this);

        huntSequence.AddNode(dissapear);
        huntSequence.AddNode(hunted);

        // START
        m_AI.StartCoroutine(m_AI.Execute());
    }
Ejemplo n.º 24
0
        public override void Run()
        {
            blackBoard = new TestBlackboard(typeof(TestBlackboard.Vars));
            tree       = new TestTree(blackBoard, this);

            blackBoard.setData(TestBlackboard.Vars.FirePower, 5d);
            blackBoard.setData(TestBlackboard.Vars.LastScan, -10d);
            blackBoard.setData(TestBlackboard.Vars.ScanDelay, 5d);
            blackBoard.setData(TestBlackboard.Vars.MaxDist, 300d);

            //Build Tree
            {
                DecoratorNode repeater = new RepeatUntilWinNode();
                tree.SetMaster(repeater);
                CompositeNode sequencer = new SequenceNode();
                repeater.setChild(sequencer);
                //Scanning
                {
                    DecoratorNode scanInverter1 = new InverterNode();
                    sequencer.addChild(scanInverter1);
                    CompositeNode scanSequencer = new SequenceNode();
                    scanInverter1.setChild(scanSequencer);

                    DecoratorNode scanInverter2 = new InverterNode();
                    scanSequencer.addChild(new ChangeColorNode(Color.Blue));
                    scanSequencer.addChild(scanInverter2);
                    scanInverter2.setChild(new RecentlyScannedNode());
                    scanSequencer.addChild(new ScanNode());
                }
                CompositeNode selector = new SelectorNode();
                sequencer.addChild(selector);
                //Move to range
                {
                    CompositeNode MoveToRangeSequencer = new SequenceNode();
                    selector.addChild(MoveToRangeSequencer);

                    MoveToRangeSequencer.addChild(new ChangeColorNode(Color.Green));
                    MoveToRangeSequencer.addChild(new RecentlyScannedNode());
                    DecoratorNode MoveToRangeInverter = new InverterNode();
                    MoveToRangeSequencer.addChild(MoveToRangeInverter);
                    MoveToRangeInverter.setChild(new InRangeNode());
                    MoveToRangeSequencer.addChild(new TurnTowardsNode());
                    MoveToRangeSequencer.addChild(new DriveNode());
                }
                // Shooting
                {
                    CompositeNode shootingSequencer = new SequenceNode();
                    selector.addChild(shootingSequencer);
                    shootingSequencer.addChild(new ChangeColorNode(Color.Red));
                    shootingSequencer.addChild(new CheckGunHeatNode());
                    shootingSequencer.addChild(new ScanNode());
                    shootingSequencer.addChild(new ShootNode());
                }
                selector.addChild(new DoNothingNode());
            }
            Out.WriteLine("Created Behaviour tree");

            //Run Tree
            {
                BTNode.Status s;
                do
                {
                    s = tree.process();
                }while(s == BTNode.Status.Running);
            }
        }
Ejemplo n.º 25
0
    public void Update()
    {
        //Parse input from the user.
        float horiz = Input.GetAxis("Horizontal");
        float vert  = Input.GetAxis("Vertical");
        float jump  = Input.GetAxis("Jump");
        float fire  = Input.GetAxis("Close");

        float horiz_mag = Mathf.Abs(horiz);
        float vert_mag  = Mathf.Abs(vert);

        if (horiz_mag < Mathf.Abs(oldHoriz))
        {
            horiz_hasFallen = true;
        }

        if (vert_mag < Mathf.Abs(oldVert))
        {
            vert_hasFallen = true;
        }

        Direction dir = Direction.None;

        if (horiz_mag > .5 && vert_mag < .5 && horiz_hasFallen)
        {
            if (horiz > 0 && horiz > oldHoriz)
            {
                dir             = Direction.Right;
                horiz_hasFallen = false;
            }
            else if (horiz < 0 && horiz < oldHoriz)
            {
                dir             = Direction.Left;
                horiz_hasFallen = false;
            }
        }
        else if (horiz_mag < .5 && vert_mag > .5 && vert_hasFallen)
        {
            if (vert > 0 && vert > oldVert)
            {
                dir            = Direction.Up;
                vert_hasFallen = false;
            }
            else if (vert < 0 && vert < oldVert)
            {
                dir            = Direction.Down;
                vert_hasFallen = false;
            }
        }

        if (dir != Direction.None)
        {
            currentMenu.GetComponent <MoveSelector_Child>().input(dir);

            //Process change in description if it's needed.

            updateDescription();
        }

        if (jump < oldJump)
        {
            jump_hasFallen = true;
        }

        if (jump > oldJump && oldJump == 0 && takeControl)
        {
            jump_hasFallen = false;
            int          sel = currentMenu.GetComponent <MoveSelector_Child>().currentSelection;
            SelectorNode selected;

            try
            {
                selected = current.children[sel];
            }
            catch (ArgumentOutOfRangeException e)
            {
                selected = current.children[0];
            }

            if (selected.hasChildren())
            {
                if (selected.children.Count > 0)
                {
                    current = selected;
                    updateDisplay();
                }
            }
            else
            {
                if (selected.name == "run")
                {
                    GameController.player.addSelectedMove("Run");
                    return;
                }
                object selectedObj = selections[selected.name];

                if (types[selected.name] == "item")
                {
                    Item selectedItem = (Item)selections[selected.name];
                    selectedItem.affectPlayer(GameController.player);

                    GameController.player.removeItemByName(selectedItem.getName());
                    items.removeChildByName(selectedItem.getName());

                    GameController.player.addSelectedMove("Item Use");

                    current = root;
                }
                else if (types[selected.name] == "move")
                {
                    Debug.Log(selected.name);
                    GameController.player.addSelectedMove(selected.name);

                    current = root;
                }

                updateDisplay();
            }
        }

        if (fire < oldFire)
        {
            fire_hasFallen = true;
        }

        if (fire > oldFire && fire_hasFallen)
        {
            fire_hasFallen = false;
            if (current != root)
            {
                current = current.parent;
            }
            updateDisplay();
        }

        oldHoriz = horiz;
        oldVert  = vert;
        oldJump  = jump;
        oldFire  = fire;

        if (currentMenu.GetComponent <MoveSelector_Child>().type != currentType)
        {
            updateDisplay();
        }
    }
Ejemplo n.º 26
0
        protected override SelectorNode CreateBehaviour()
        {
            //Create the reposition nodes
            SafetyCheckNode safetyCheckNode = new SafetyCheckNode(this);

            DelegateNode.Delegate invincibleFunc        = SetInvincible;
            DelegateNode          setInvincibleTrueNode = new DelegateNode(this, invincibleFunc, true);

            AnimatorNode jumpAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsInannaJumping", ref m_JumpLink);

            LerpNode lerpUpwardsNode = new LerpNode(this, Vector3.up, JumpToMaxTime, JumpHeight, JumpSpeed);

            //Grab all tower points in the map
            GameObject[] towerPointGameObjects = GameObject.FindGameObjectsWithTag("TowerPoint");
            Transform[]  towerPointTransforms  = new Transform[towerPointGameObjects.Length];

            for (int i = 0; i < towerPointTransforms.Length; i++)
            {
                towerPointTransforms[i] = towerPointGameObjects[i].transform;
            }

            InannaMoveTowerNode moveTowerNode          = new InannaMoveTowerNode(this, towerPointTransforms);
            LerpNode            lerpDownwardsNode      = new LerpNode(this, Vector3.down, JumpToMaxTime, JumpHeight, JumpSpeed);
            AnimatorNode        landAnimationNode      = new AnimatorNode(this, m_AnimatorRef, "IsInannaLanding", ref m_LandingLink);
            PlaySoundNode       InnanaJumpSoundNode    = new PlaySoundNode(this, "WingFlap");
            DelegateNode        setInvincibleFalseNode = new DelegateNode(this, invincibleFunc, false);

            //Create reposition sequence

            SequenceNode repositionSequence = new SequenceNode(this, "RepositionSequence", safetyCheckNode, setInvincibleTrueNode, jumpAnimationNode, InnanaJumpSoundNode, lerpUpwardsNode, moveTowerNode, lerpDownwardsNode, InnanaJumpSoundNode, landAnimationNode, setInvincibleFalseNode);

            //Create arrow rain nodes
            PlaySoundNode             ArrowRainSound        = new PlaySoundNode(this, "ArrowRain", 8.0f);
            RainOfArrowsCooldownNode  arrowRainCooldownNode = new RainOfArrowsCooldownNode(this, RainOfArrowsCooldown, RainOfArrowsDiameter);
            RainOfArrowsTargetingNode arrowRainTargetNode   = new RainOfArrowsTargetingNode(this, RainOfArrowsDiameter);
            AnimatorNode           arrowRainAnimationNode   = new AnimatorNode(this, m_AnimatorRef, "IsFiringRainOfArrows", ref m_ArrowRainShotLink);
            RainOfArrowsAttackNode arrowRainAttackNode      = new RainOfArrowsAttackNode(this, m_CircularAOEPrefab.GetComponent <CircularAOE>(), RainOfArrowsWaitTime);

            //Create arrow rain sequence
            SequenceNode arrowRainSequence = new SequenceNode(this, "RainOfArrowsSequence", arrowRainCooldownNode, arrowRainTargetNode, arrowRainAnimationNode, arrowRainAttackNode, ArrowRainSound);

            //Create snipe shot nodes
            PlaySoundNode   HeavyShotSound     = new PlaySoundNode(this, "HeavyShot");
            SnipeDelayNode  snipeDelayNode     = new SnipeDelayNode(this, m_Ereshkigal.transform, m_LineRenderer, m_Ereshkigal.EreshkigalSafeSpace, HitScanBuildUp);
            AnimatorNode    snipeAnimationNode = new AnimatorNode(this, m_AnimatorRef, "IsSniping", ref m_SnipeShotLink);
            HitScanShotNode hitScanShotNode    = new HitScanShotNode(this, ShootLocation.transform, m_HitScanShot, HitscanShotDamage, HitScanShotDelay);

            //Create snipe sequence
            SequenceNode snipeSequence = new SequenceNode(this, "SnipeSequence", snipeDelayNode, snipeAnimationNode, hitScanShotNode, HeavyShotSound);

            //Create arrow shot targeting nodes
            TargetingDistanceFromLocationGreaterThenNode targetingDistanceNode = new TargetingDistanceFromLocationGreaterThenNode(this, m_Ereshkigal.transform, m_Ereshkigal.EreshkigalSafeSpace * 0.5f, 2);
            TargetingLowHealthNode     targetingLowestHPNode      = new TargetingLowHealthNode(this, 2);
            TargetingHighestDamageNode targetingHighestDamageNode = new TargetingHighestDamageNode(this, 1);
            TargetingSightNode         targetingSightNode         = new TargetingSightNode(this, 1, true);
            CalculateTargetNode        calculateTargetNode        = new CalculateTargetNode(this);

            //Create arrow shot targeting sequence
            SequenceNode targetingSequence = new SequenceNode(this, "ArrowTargetingSequence", targetingDistanceNode, targetingLowestHPNode, targetingHighestDamageNode, targetingSightNode, calculateTargetNode);

            //Create other arrow shot nodes
            PlaySoundNode       ArrowShotSoundNode      = new PlaySoundNode(this, "ArrowFire");
            CooldownNode        arrowShotCooldownNode   = new CooldownNode(this, ArrowShotRate);
            AnimatorNode        arrowShotAnimationNode  = new AnimatorNode(this, m_AnimatorRef, "IsFiringArrowShot", ref m_RegularShotLink);
            ShootProjectileNode arrowShotProjectileNode = new ShootProjectileNode(this, ArrowShotDamage, ArrowProjectilePrefab, ShootLocation, "InannaArrowPool", 5);

            //Create arrow shot sequence
            SequenceNode arrowShotSequence = new SequenceNode(this, "ArrowShotSequence", targetingSequence, arrowShotCooldownNode, arrowShotAnimationNode, ArrowShotSoundNode, arrowShotProjectileNode);

            //Create utility selector
            SelectorNode utilitySelector = new SelectorNode(this, "InannaUtilitySelector", repositionSequence, arrowRainSequence, snipeSequence, arrowShotSequence);

            return(utilitySelector);
        }
Ejemplo n.º 27
0
    public void Start()
    {
        /*if (GameController.player == null) {
         *  GameController.player = new PlayerCharacter();
         *  Debug.LogWarning("Can't find PlayerCharacter script in the scene. This may cause issues.");
         * }*/

        takeControl = true;
        Debug.Log("Player in Move Selector: " + GameController.player.strength);

        /*if(GameController.player == null) {
         *  Debug.LogWarning("There is no fighter class attached to the move selector. I'm creating a fake player for testing purposes.");
         *  GameController.player = new PlayerCharacter();
         *  GameController.player.testInventory();
         * }*/
        if (GameController.player.name == "[Test_inv]")
        {
            GameController.player.testInventory();
        }

        MoveUtils.InitMoves();

        selections = new Dictionary <string, object>();
        types      = new Dictionary <string, string>();

        selectorMap = new Dictionary <SelectorType, GameObject>();
        selectorMap[SelectorType.Loop]     = loopObject;
        selectorMap[SelectorType.Grid]     = gridObject;
        selectorMap[SelectorType.In_Place] = inPlaceObject;

        root = new SelectorNode("root", "ROOT", new List <SelectorNode>(), SelectorType.Grid);

        SelectorNode moves = new SelectorNode("moves", "Moves", new List <SelectorNode>(), SelectorType.Loop);

        root.addChild(moves);

        foreach (Move m in GameController.player.getMoves())
        {
            selections.Add(m.name, MoveUtils.GetMove(m.name));
            types.Add(m.name, "move");
            moves.addChild(new SelectorNode(m.name, m.name));
        }

        items = new SelectorNode("items", "Items", new List <SelectorNode>(), SelectorType.Loop);
        root.addChild(items);

        if (GameController.player.inventory.Count > 0)
        {
            foreach (Item item in GameController.player.inventory)
            {
                Debug.Log(item.getName());
                if (item.getName() != "Rock" && item.getName() != "Ladder")
                {
                    selections.Add(item.getName(), item);
                    types.Add(item.getName(), "item");
                    items.addChild(new SelectorNode(item.getName(), item.getDisplayName()));
                }
            }
        }



        SelectorNode options = new SelectorNode("run", "Run");

        root.addChild(options);

        SelectorNode special = new SelectorNode("special", "Special", new List <SelectorNode>(), SelectorType.Loop);

        root.addChild(special);

        current = root;

        updateDisplay();
    }
Ejemplo n.º 28
0
    private static BaseNode __addNode(NodeType node_type, Vector2 mousePosition)
    {
        BaseNode node = null;

        switch (node_type)
        {
        case NodeType.BehaviourNode:
            node = new BehaviourNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.ExcelNode:
            node = new ExcelNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <ExcelNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.ActionNode:
            node = new ActionNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.ConditionNode:
            node = new ConditionNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.WaitNode:
            node = new WaitNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.SequenceNode:
            node = new SequenceNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.SelectorNode:
            node = new SelectorNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;

        case NodeType.LoopNode:
            node = new LoopNode();
            node.Init(mousePosition, OnClickNode);
            NodeDataManager.CreateNodeData <BaseNodeData>(node);
            nodes_list.Add(node);
            break;
        }

        if (node != null && nodes_list.Count == 1)
        {
            rootNode = node;
        }
        return(node);
    }
Ejemplo n.º 29
0
    public static BehaviorNode InitRootNode(BehaviorTree behaviorTree, AbstractActor unit, GameInstance game)
    {
        LanceHasLOSNode lanceHasLOS0000 = new LanceHasLOSNode("lanceHasLOS0000", behaviorTree, unit);

        FindVisibleEnemiesNode findVisibleEnemies0000 = new FindVisibleEnemiesNode("findVisibleEnemies0000", behaviorTree, unit);

        IsMovementAvailableForUnitNode movementAvailable0000 = new IsMovementAvailableForUnitNode("movementAvailable0000", behaviorTree, unit);

        SortEnemiesByThreatNode sortEnemiesByThreat0000 = new SortEnemiesByThreatNode("sortEnemiesByThreat0000", behaviorTree, unit);

        MoveTowardsHighestPriorityEnemyNode moveTowardsHighestPriorityEnemy0000 = new MoveTowardsHighestPriorityEnemyNode("moveTowardsHighestPriorityEnemy0000", behaviorTree, unit);

        SequenceNode canMove = new SequenceNode("canMove", behaviorTree, unit);

        canMove.AddChild(movementAvailable0000);
        canMove.AddChild(sortEnemiesByThreat0000);
        canMove.AddChild(moveTowardsHighestPriorityEnemy0000);

        IsAttackAvailableForUnitNode attackAvailable0000 = new IsAttackAvailableForUnitNode("attackAvailable0000", behaviorTree, unit);

        SortEnemiesByEffectivenessNode sortEnemiesByEffectiveness0000 = new SortEnemiesByEffectivenessNode("sortEnemiesByEffectiveness0000", behaviorTree, unit);

        ShootAtHighestPriorityEnemyNode shootAtHighestPriorityEnemy0000 = new ShootAtHighestPriorityEnemyNode("shootAtHighestPriorityEnemy0000", behaviorTree, unit);

        SequenceNode canAttack = new SequenceNode("canAttack", behaviorTree, unit);

        canAttack.AddChild(attackAvailable0000);
        canAttack.AddChild(sortEnemiesByEffectiveness0000);
        canAttack.AddChild(shootAtHighestPriorityEnemy0000);

        SelectorNode selector0000 = new SelectorNode("selector0000", behaviorTree, unit);

        selector0000.AddChild(canMove);
        selector0000.AddChild(canAttack);

        SequenceNode free_engage = new SequenceNode("free_engage", behaviorTree, unit);

        free_engage.AddChild(lanceHasLOS0000);
        free_engage.AddChild(findVisibleEnemies0000);
        free_engage.AddChild(selector0000);

        IsMovementAvailableForUnitNode movementAvailable0001 = new IsMovementAvailableForUnitNode("movementAvailable0001", behaviorTree, unit);

        FindPreviouslySeenEnemiesNode findPreviouslySeenEnemies0000 = new FindPreviouslySeenEnemiesNode("findPreviouslySeenEnemies0000", behaviorTree, unit);

        SortEnemiesByProximityNode sortEnemiesByProximity0000 = new SortEnemiesByProximityNode("sortEnemiesByProximity0000", behaviorTree, unit);

        MoveTowardsHighestPriorityEnemyNode moveTowardsHighestPriorityEnemy0001 = new MoveTowardsHighestPriorityEnemyNode("moveTowardsHighestPriorityEnemy0001", behaviorTree, unit);

        SequenceNode hunt_previously_seen = new SequenceNode("hunt_previously_seen", behaviorTree, unit);

        hunt_previously_seen.AddChild(movementAvailable0001);
        hunt_previously_seen.AddChild(findPreviouslySeenEnemies0000);
        hunt_previously_seen.AddChild(sortEnemiesByProximity0000);
        hunt_previously_seen.AddChild(moveTowardsHighestPriorityEnemy0001);

        SelectorNode selector0001 = new SelectorNode("selector0001", behaviorTree, unit);

        selector0001.AddChild(hunt_previously_seen);

        FailNode fail0000 = new FailNode("fail0000", behaviorTree, unit);

        SelectorNode patrol = new SelectorNode("patrol", behaviorTree, unit);

        patrol.AddChild(fail0000);

        BraceNode brace0000 = new BraceNode("brace0000", behaviorTree, unit);

        SelectorNode dumb_AI_root = new SelectorNode("dumb_AI_root", behaviorTree, unit);

        dumb_AI_root.AddChild(free_engage);
        dumb_AI_root.AddChild(selector0001);
        dumb_AI_root.AddChild(patrol);
        dumb_AI_root.AddChild(brace0000);

        return(dumb_AI_root);
    }
Ejemplo n.º 30
0
 /// <summary>
 /// clone
 /// </summary>
 /// <returns></returns>
 public IBehaviourNode Clone()
 {
     var behaviourNode = new SelectorNode();
     base.CopyToCompositeNode(behaviourNode);
     return behaviourNode;
 }
Ejemplo n.º 31
0
 protected override void FillTreeWithData(ObjectSelectorEditor.Selector selector, ITypeDescriptorContext context, IServiceProvider provider)
 {
     base.FillTreeWithData(selector, context, provider);
     CardPanel Panel = (CardPanel)context.Instance;
     foreach (CardPanelPage Page in Panel.Controls)
     {
         SelectorNode Node = new SelectorNode(Page.Name, Page);
         selector.Nodes.Add(Node);
         if (Page == Panel.SelectedItem)
         {
             selector.SelectedNode = Node;
         }
     }
 }
	// Methods
	public SelectorNode AddNode(string label, object value, SelectorNode parent) {}
Ejemplo n.º 33
0
			public SelectorNode AddNode (string label, object value, SelectorNode parent)
			{
				throw new NotImplementedException ();
			}
Ejemplo n.º 34
0
        public ApproachMachine()
        {
            DataStorage[PlayerPosition] = new Point(10, 10);
            DataStorage[GoalPosition]   = new Point(0, 0);
            DataStorage[Switch]         = false;

            var switchOffState = new State();

            this[SwitchOff] = switchOffState;
            switchOffState.OnExecuteEvent = (machine, state) =>
            {
                Debug.WriteLine($"SwitchOff");
                if ((bool)machine.DataStorage[Switch])
                {
                    machine.NextStateName = SwitchOn;
                }
            };

            var switchOnState = new State();

            this[SwitchOn] = switchOnState;

            var behaviourMachine = new BehaviourMachine();

            behaviourMachine.DataStorage.ReferTo(DataStorage, PlayerPosition);
            behaviourMachine.DataStorage.ReferTo(DataStorage, GoalPosition);

            switchOnState.OnExecuteEvent = (machine, state) =>
            {
                Debug.WriteLine($"SwitchOn");
                behaviourMachine.Execute();
            };

            var moveOrTeleportSelector = new SelectorNode();

            behaviourMachine.RegisterRootNode(moveOrTeleportSelector);

            var moveDecorator = new DecoratorNode();

            moveOrTeleportSelector.ChildNodes.Add(moveDecorator);
            moveDecorator.ConditionCallback = (machine, node) =>
            {
                Debug.WriteLine($"move condition check");
                var playerPosition = (Point)machine.DataStorage[PlayerPosition];
                var goalPosition   = (Point)machine.DataStorage[GoalPosition];
                Debug.WriteLine($"P:{playerPosition} G:{goalPosition}");
                return(!playerPosition.Equals(goalPosition));
            };
            var moveAction = new ActionNode();

            moveDecorator.ChildNode   = moveAction;
            moveAction.ActionCallback = (machine, node) =>
            {
                Debug.WriteLine($"Move");
                var playerPosition = (Point)machine.DataStorage[PlayerPosition];
                var goalPosition   = (Point)machine.DataStorage[GoalPosition];
                var diffX          = Math.Abs(playerPosition.X - goalPosition.X);
                var diffY          = Math.Abs(playerPosition.Y - goalPosition.Y);
                if (diffX >= diffY)
                {
                    playerPosition.X += playerPosition.X > goalPosition.X ? -1 : 1;
                }
                else
                {
                    playerPosition.Y += playerPosition.Y > goalPosition.Y ? -1 : 1;
                }
                machine.DataStorage[PlayerPosition] = playerPosition;
                return(true);
            };

            var teleportAction = new ActionNode();

            teleportAction.DataStorage[TeleportCounter] = 10;
            moveOrTeleportSelector.ChildNodes.Add(teleportAction);
            teleportAction.ActionCallback = (machine, node) =>
            {
                Debug.WriteLine($"teleport");
                var teleportCounter = (int)node.DataStorage[TeleportCounter];
                teleportCounter--;
                node.DataStorage[TeleportCounter] = teleportCounter;
                Debug.WriteLine($"teleport counter: {teleportCounter}");
                if (teleportCounter > 0)
                {
                    return(false);
                }

                var playerPosition = (Point)machine.DataStorage[PlayerPosition];
                playerPosition.X = new Random().Next(-10, 10);
                playerPosition.Y = new Random().Next(-10, 10);
                machine.DataStorage[PlayerPosition] = playerPosition;

                node.DataStorage[TeleportCounter] = 10;
                Debug.WriteLine($"teleport to {playerPosition}");
                return(true);
            };
        }
Ejemplo n.º 35
0
        protected override SelectorNode CreateBehaviour()
        {
            #region Spectral Chain Sequence
            //being section that deals with the attack
            #region Create the sequence for attacking
            //when ere begins to move to the center of the map she does it through this node
            AgentMoveToLocationNode moveToLocation = new AgentMoveToLocationNode(this, m_RoomCenter.position);
            //When ere's animation of her raising the chain happens
            AnimatorNode chainRaiseNode = new AnimatorNode(this, m_AnimatorRef, "IsChainRaising", ref m_SpearRaiseLink);
            //the chain move to player node which will move the chain to the player
            ChainMoveToPlayersNode chainMoveToPlayer = new ChainMoveToPlayersNode(this, SpearTipLocation, m_LineRenderer, ChainTravelTime);
            //this node determines if the chain attack is done
            HasChainReturnedNode hasChainReturned = new HasChainReturnedNode(this);
            AnimatorNode         chainLowerNode   = new AnimatorNode(this, m_AnimatorRef, "IsChainLowering", ref m_SpearLowerLink);
            PlaySoundNode        ChainSoundNode   = new PlaySoundNode(this, "ChainSound");


            //tieing all the nodes into the sequence

            SequenceNode chainAttackSection = new SequenceNode(this, "Spectral Chain Attack", moveToLocation, chainRaiseNode, chainMoveToPlayer, hasChainReturned, chainLowerNode);
            #endregion

            #region Target Selection region
            //determines if to much time has passed away from center of the map
            TimeAwayFromCenterNode timeAwayFromCenter = new TimeAwayFromCenterNode(this, m_RoomCenter.position, CenterMapSafeSpace, MaxWaitTimeAwayFromCenter);
            //determines the player's distance from Inanna
            PlayerToCloseTargetNode playerToCloseToTargetNode = new PlayerToCloseTargetNode(this, m_Inanna.transform, MinimumDistanceToTarget);

            SelectorNode spectralChainAttackSelector = new SelectorNode(this, "Choose Attack Selector Spectral Chain", timeAwayFromCenter, playerToCloseToTargetNode);
            #endregion
            //cooldown node for spectral chain
            CooldownNode spectralChainCooldown = new CooldownNode(this, SpectralChainCooldown);
            //determines if Ere can still use chain attack
            CanUseChainsNode canUseChain = new CanUseChainsNode(this, MaxChainCyclesPerCycle);


            SequenceNode specrtalChainSequence = new SequenceNode(this, "Spectral Chain Sequence", spectralChainCooldown, canUseChain, spectralChainAttackSelector, ChainSoundNode, chainAttackSection);
            #endregion

            #region Ereshkigal Attack Sequence

            #region Target Selector
            #region Protecting Inanna Sequence
            //puts points into anyone to far away from Ere
            TargetingDistanceFromLocationGreaterThenNode distanceFromEre = new TargetingDistanceFromLocationGreaterThenNode(this, transform, EreshkigalSafeSpace, 1);
            //puts points into anyone to close to Anna
            TargetingDistanceFromLocationNode distanceFromAnna = new TargetingDistanceFromLocationNode(this, m_Inanna.transform, MinimumDistanceToTarget, 2);
            CalculateTargetNode calcTarget = new CalculateTargetNode(this);
            SequenceNode        protectingInannaSequence = new SequenceNode(this, "Protecting Inanna Sequence", distanceFromEre, distanceFromAnna, calcTarget);
            #endregion

            TargetFollowUp   followup         = new TargetFollowUp(this);
            TargetSwitchNode switchTargetNode = new TargetSwitchNode(this);

            SelectorNode targetingSelector = new SelectorNode(this, "Taregting Selector", protectingInannaSequence, followup, switchTargetNode);
            #endregion

            #region Lunge Attack
            CooldownNode           lungeCooldown  = new CooldownNode(this, LungeCooldown);
            ToggleNavMeshAgentNode toggleAgentOff = new ToggleNavMeshAgentNode(this);
            //the crouch before the big jump animator node
            AnimatorNode preJump = new AnimatorNode(this, m_AnimatorRef, "IsPreJumping", ref m_PreJumpLink);
            //lerp and animation which will run in tandum
            LerpNode       jumpLerp            = new LerpNode(this, Vector3.up, 1.0f, JumpHeight, JumpSpeed);
            AnimatorNode   fulljump            = new AnimatorNode(this, m_AnimatorRef, "IsFullJumping", ref m_JumpLink);
            RunUntilSuceed runJumpAndAnimation = new RunUntilSuceed(this, "Run Animation and Jump", fulljump, jumpLerp);
            PlaySoundNode  LungeSoundNode      = new PlaySoundNode(this, "HeavyAttack2");
            PlaySoundNode  JumpSoundNode       = new PlaySoundNode(this, "WingFlap");
            PlaySoundNode  ScreamSoundNode     = new PlaySoundNode(this, "EreshkigalScream");



            AnimatorNode            jumpIdle         = new AnimatorNode(this, m_AnimatorRef, "IsJumpIdle", ref m_JumpIdleLink);
            LookAtTargetNode        lookAtTarget     = new LookAtTargetNode(this);
            ToggleMeleeColliderNode toggleLungeOn    = new ToggleMeleeColliderNode(this, SpearCollider, LungeDamage);
            AnimatorNode            diveAnimation    = new AnimatorNode(this, m_AnimatorRef, "IsDiving", ref m_DiveLink);
            LerpToTargetNode        diveLerp         = new LerpToTargetNode(this, DiveTime, JumpHeight, DiveSpeed);
            RunUntilSuceed          diveAtPlayer     = new RunUntilSuceed(this, "Run Dive and Animation", diveAnimation, diveLerp);
            ToggleMeleeColliderNode toggleLungeOff   = new ToggleMeleeColliderNode(this, SpearCollider, 0);
            ToggleNavMeshAgentNode  toggleAgentOn    = new ToggleNavMeshAgentNode(this);
            AnimatorNode            diveRecoveryNode = new AnimatorNode(this, m_AnimatorRef, "IsInDiveRecovery", ref m_DiveRecoverLink);

            SequenceNode lungeAttackSequence = new SequenceNode(this, "Lunge Attack Sequence",
                                                                lungeCooldown,
                                                                toggleAgentOff,
                                                                preJump,
                                                                runJumpAndAnimation,
                                                                JumpSoundNode,
                                                                jumpIdle,
                                                                toggleLungeOn,
                                                                lookAtTarget,
                                                                ScreamSoundNode,
                                                                diveAtPlayer,
                                                                JumpSoundNode,
                                                                toggleLungeOff,
                                                                toggleAgentOn,
                                                                diveRecoveryNode);
            #endregion

            #region Spear Toss Attack
            CooldownNode        spearTossCooldown          = new CooldownNode(this, SpearThrowCooldown);
            AnimatorNode        spearThrowAnimator         = new AnimatorNode(this, m_AnimatorRef, "IsSpearBeingThrow", ref m_SpearThrowLink);
            ShootProjectileNode spearProjectileShoot       = new ShootProjectileNode(this, SpearThrowDamage, SpearProjectilePrefab, SpearThrowLocation.gameObject, "SpearProjectile", 2);
            AnimatorNode        spearThrowRecoveryAnimator = new AnimatorNode(this, m_AnimatorRef, "IsInSpearRecovery", ref m_SpearThrowRecoveryLink);

            SequenceNode spearTossSequence = new SequenceNode(this, "Spear Toss Sequence", spearTossCooldown, spearThrowAnimator, spearProjectileShoot, LungeSoundNode, spearThrowRecoveryAnimator);
            #endregion

            #region Basic Attack Selector

            #region 360 Attack
            CheckDistanceToTargetNode attack360DistanceCheck = new CheckDistanceToTargetNode(this, Agent.stoppingDistance);
            AnimatorNode            buildUp360           = new AnimatorNode(this, m_AnimatorRef, "IsIn360BuildUp", ref m_360BuildUpLink);
            ToggleMeleeColliderNode toggleOn360Collider  = new ToggleMeleeColliderNode(this, SpearCollider, SpearAttack360Damage);
            AnimatorNode            swing360             = new AnimatorNode(this, m_AnimatorRef, "IsIn360Swing", ref m_360SwingLink);
            ToggleMeleeColliderNode toggleOff360Collider = new ToggleMeleeColliderNode(this, SpearCollider, 0);
            AnimatorNode            recovery360          = new AnimatorNode(this, m_AnimatorRef, "IsIn360Recovery", ref m_360RecoveryLink);

            SequenceNode sequence360Attack = new SequenceNode(this, "360 Attack Sequence", attack360DistanceCheck, buildUp360, toggleOn360Collider, swing360, LungeSoundNode, toggleOff360Collider, recovery360);
            #endregion

            #region Upper Stab
            PlaySoundNode             MedThrustSound           = new PlaySoundNode(this, "MedAttack3");
            CheckDistanceToTargetNode attackUpperStab          = new CheckDistanceToTargetNode(this, Agent.stoppingDistance);
            AnimatorNode            buildUpUpperStab           = new AnimatorNode(this, m_AnimatorRef, "IsInUpperStabBuildUp", ref m_UpperStabBuildUpLink);
            ToggleMeleeColliderNode toggleOnUpperStabCollider  = new ToggleMeleeColliderNode(this, SpearCollider, SpearAttackUpperStabDamage);
            AnimatorNode            swingUpperStab             = new AnimatorNode(this, m_AnimatorRef, "IsInUpperStabSwing", ref m_UpperStabSwingLink);
            ToggleMeleeColliderNode toggleOffUpperStabCollider = new ToggleMeleeColliderNode(this, SpearCollider, 0);
            AnimatorNode            recoveryUpperStab          = new AnimatorNode(this, m_AnimatorRef, "IsInUpperStabRecovery", ref m_UpperStabRecoveryLink);

            SequenceNode sequenceUpperStabAttack = new SequenceNode(this, "Upper Stab Sequence", attackUpperStab, buildUpUpperStab, toggleOnUpperStabCollider, swingUpperStab, MedThrustSound, toggleOffUpperStabCollider, recoveryUpperStab);
            #endregion

            #region Jab
            PlaySoundNode             PlayLightThrustSound   = new PlaySoundNode(this, "LightAttack2");
            CheckDistanceToTargetNode attackJabDistanceCheck = new CheckDistanceToTargetNode(this, Agent.stoppingDistance);
            AnimatorNode            buildUpJab           = new AnimatorNode(this, m_AnimatorRef, "IsInJabBuildUp", ref m_JabBuildUpLink);
            ToggleMeleeColliderNode toggleOnJabCollider  = new ToggleMeleeColliderNode(this, SpearCollider, SpearAttackJabDamage);
            AnimatorNode            swingJab             = new AnimatorNode(this, m_AnimatorRef, "IsInJabSwing", ref m_JabSwingLink);
            ToggleMeleeColliderNode toggleOffJabCollider = new ToggleMeleeColliderNode(this, SpearCollider, 0);
            AnimatorNode            recoveryJab          = new AnimatorNode(this, m_AnimatorRef, "IsInJabRecovery", ref m_JabRecoveryLink);

            SequenceNode sequenceJabAttack = new SequenceNode(this, "Jab Attack Sequence", attackJabDistanceCheck, buildUpJab, toggleOnJabCollider, swingJab, PlayLightThrustSound, toggleOffJabCollider, recoveryJab);
            #endregion

            ChooseRandomChildNode randomBasicAttackSelector = new ChooseRandomChildNode(this, "Basic Attack Selector, Random", sequence360Attack, sequenceJabAttack, sequenceUpperStabAttack);
            #endregion

            ApproachNode approachTargetPlayer     = new ApproachNode(this);
            SelectorNode chooseAttackSelector     = new SelectorNode(this, "Attack Choosing Selector", lungeAttackSequence, spearTossSequence, randomBasicAttackSelector, approachTargetPlayer);
            SequenceNode ereshkigalAttackSequence = new SequenceNode(this, "Ereshkigal Basic Attack Sequence", targetingSelector, chooseAttackSelector);
            #endregion

            SelectorNode utilitySelector = new SelectorNode(this, "UtilitySelector", specrtalChainSequence, ereshkigalAttackSequence);

            return(utilitySelector);
        }
Ejemplo n.º 36
0
 public override string Visit(SelectorNode node, CssVisitorParams p)
 {
     return(node.Selector.Value);
 }
Ejemplo n.º 37
0
 public SelectorNode AddNode(string label, object value, SelectorNode parent)
 {
     throw null;
 }
Ejemplo n.º 38
0
 /// <summary>The <see cref="Ast.Selectors.SelectorNode"/> visit implementation</summary>
 /// <param name="selectorNode">The selector AST node</param>
 /// <returns>The modified AST node if modified otherwise the original node</returns>
 public virtual AstNode VisitSelectorNode(SelectorNode selectorNode)
 {
     return(selectorNode);
 }
Ejemplo n.º 39
0
 public virtual R Visit(SelectorNode node, P p)
 {
     return(default(R));
 }
Ejemplo n.º 40
0
    /// <summary>
    /// CSS-inspired, simplified selector matching.
    /// </summary>
    protected bool DoesSelectorMatchDescriptorChain(SelectorNode[] selectorChain, VisualizationDescriptor[] descriptorChain)
    {
        //
        // Algorithm: Starting at the leaf selector node and leaf descriptor node,
        // we move up both chains, acknowledging compatible node pairs on the way up.
        // The ParentRelationship value is important in permitting descriptor nodes
        // to be skipped or not. The algorithm terminates with a match if we have fully traversed
        // up the selector chain without finding any incompatibility between the chains,
        // and terminates without a match if otherwise.
        //

        VisualizationDescriptor descriptorNode = descriptorChain.LastOrDefault();
        bool isLeafMatched = false;
        for (int i = selectorChain.Length - 1; i >= 0; --i)
        {
            if (descriptorNode == null)
            {
                // Ran out of descriptor nodes, thus the selector was not fully matched.
                return false;
            }
            SelectorNode selectorNode = selectorChain[i];
            if ((selectorNode.Class != null && selectorNode.Class != descriptorNode.Class)
                || (selectorNode.Type != null && selectorNode.Type != descriptorNode.TargetType.Name))
            {
                if (isLeafMatched)
                {
                    // Not a matching node.
                    if (selectorNode.ParentRelationship == SelectorNode.SelectorNodeRelationship.Direct)
                    {
                        // We needed to have directly matched the parent here or bust.
                        return false;
                    }
                    else
                    {
                        // Let's keep our selector position, but move up the descriptor chain.
                        i++;
                        descriptorNode = descriptorNode.ParentDescriptor;
                        continue;
                    }
                }
                else
                {
                    // We needed to at least match the leaf node.
                    return false;
                }
            }
            else
            {
                // Found a match.
                if (!isLeafMatched)
                {
                    isLeafMatched = true;
                }
                descriptorNode = descriptorNode.ParentDescriptor;
            }
        }

        // Completed traversal of the selector chain without returning early.
        // Complete match.
        return true;
    }