Exemplo n.º 1
0
    /// <summary>
    /// Run our selected child.  If no child is selected, select one.  If can't select one, return false.
    /// </summary>
    /// <param name="tank">Tank being controlled.</param>
    /// <returns>Whether we want to continue running.</returns>
    public override bool Tick(AIInput g)
    {
        BehaviorTreeNode next = SelectChild(g);

        //Debug.Log(next);
        if (next == null)
        {
            return(false);
        }

        if (selected != next)
        {
            Deactivate(g);
            next.Activate(g);
            selected = next;
        }
        bool response = next.Tick(g);

        if (response == false)
        {
            Deactivate(g);
            sequentialChild++;
            sequentialChild %= Children.Count;
        }
        return(response);
    }
Exemplo n.º 2
0
    /// <summary>
    /// Run the specified decider and returns its value
    /// </summary>
    /// <param name="d">Decider to run</param>
    /// <param name="tank">Tank being controlled</param>
    /// <returns>True if decider wants to run</returns>
    public static bool Decide(this DeciderType d, AIInput g)
    {
        Vector3 direction = BehaviorTreeNode.Player.position - g.transform.position;

        switch (d)
        {
        case DeciderType.Always:
            return(true);

        case DeciderType.LineOfSight:
            //Debug.DrawRay(tur.transform.position + new Vector3(0, 1, 0), BehaviorTreeNode.Player.position - tur.transform.position);
            Vector3 adjust = new Vector3(0, 0.2f, 0);
            Vector3 dif    = direction - adjust;

            return(!Physics2D.Raycast(g.transform.position + adjust, direction, direction.magnitude, (1 << 8) | (1 << 10)));                 //Debug.Log(a);


        case DeciderType.FacingTarget:


            return(Vector3.Angle(g.transform.right, direction) < 10);

        case DeciderType.Threat0:
            Vector3 vec = g.threat[0];
            bool    r   = Vec3.lessThan(Vec3.Abs(direction), vec);
            return(r);

        case DeciderType.Half:
            Health h = g.GetComponent <Health>();
            return((float)(h.currentHealth) / h.maxHealth > 0.5f);

        default:
            throw new ArgumentException("Unknown Decider: " + d);
        }
    }
Exemplo n.º 3
0
 public NormalState(AIInput owner, float wanderStrength, CollisionNotifier collisionNotifier)
 {
     this.owner             = owner;
     this.wanderStrength    = wanderStrength;
     this.collisionNotifier = collisionNotifier;
     coinMask          = LayerMask.GetMask("Coin");
     collisionDelegate = new CollisionNotifier.OnCollision(OnCollision);
 }
Exemplo n.º 4
0
 /// <summary>
 /// We're not running anymore; recursively deactivate our selected child.
 /// </summary>
 /// <param name="tank">Tank being controlled</param>
 public override void Deactivate(AIInput g)
 {
     if (selected)
     {
         selected.Deactivate(g);
         selected = null;
     }
 }
Exemplo n.º 5
0
 public override void Activate(AIInput g)
 {
     // Check to make sure the subset property is satisfied
     if (!Children.Any(c => c.Decide(g)))
     {
         Debug.Log(name + " activated without runnable child");
     }
 }
Exemplo n.º 6
0
    private void Awake()
    {
        _input        = GetComponent <AIInput>();
        _stateMachine = GetComponent <StateMachine>();
        _movement     = GetComponent <Movement>();

        InitializeStateMachine();
    }
Exemplo n.º 7
0
    public override bool Tick(AIInput g)
    {
        g.moveHor(Player.transform.position);
        g.FG(Player.transform.position.x - g.transform.position.x < 0);



        return(false);
    }
Exemplo n.º 8
0
 public AggressiveState(AIInput owner, float wanderStrength, float guidePointDistance, float time, CollisionNotifier collisionNotifier)
 {
     this.owner              = owner;
     this.wanderStrength     = wanderStrength;
     this.guidePointDistance = guidePointDistance;
     maxTime = time;
     this.collisionNotifier = collisionNotifier;
     collisionDelegate      = new CollisionNotifier.OnCollision(OnCollision);
 }
Exemplo n.º 9
0
    double computeState0(AIInput input)
    {
        var transform = input.Myself.Get <TransformComponent>();

        Vector3 v1 = transform.Forward;
        Vector3 v2 = new Vector3(v1.X, 0, v1.Z);

        return(Vector3.Angle(v1, v2));
    }
Exemplo n.º 10
0
    public override bool Check(BTInput _input)
    {
        AIInput input = _input as AIInput;

        if (input != null)
        {
            return(input.CheckCondition(AIConditionType.HasTarget));
        }
        return(false);
    }
Exemplo n.º 11
0
    public override bool Check(BTInput _input)
    {
        AIInput input = _input as AIInput;

        if (input != null)
        {
            return(input.CheckCondition(AIConditionType.IsAttackRange));
        }

        return(false);
    }
Exemplo n.º 12
0
 public override bool Tick(AIInput g)
 {
     g.setCtrl(new AIInput.aiMove(Vector2.zero));
     g.stall();
     //Debug.Log("Waiting");
     if (g.waiting)
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 13
0
    protected override BTResult OnExecute(ref BTInput _input)
    {
        AIInput input = _input as AIInput;

        if (input != null)
        {
            return(input.DoAction(AIActionType.Attack));
        }

        return(base.OnExecute(ref _input));
    }
Exemplo n.º 14
0
    //Setup TrackerObject
    public void SetupAIKart()
    {
        input = GetComponent <AIInput>();
        ak    = this.GetComponent <ArcadeKart>();
        ak.SetCanMove(true);

        target = circuit.GetChild(currentWP).transform.position;

        tracker = new GameObject();
        tracker.transform.position = gameObject.transform.position;
        tracker.transform.rotation = gameObject.transform.rotation;
    }
Exemplo n.º 15
0
        public AIOutput Predict(BotConfig config, string utterance)
        {
            //attempt to find any exact matches before going to ml
            foreach (var conversation in config.Conversations)
            {
                foreach (var configuredUtterance in conversation.StartNode.Utterances)
                {
                    if (configuredUtterance.Statement.ToLower() == utterance.ToLower())
                    {
                        return(new AIOutput()
                        {
                            Prediction = conversation.ID.ToString(), ExactMatch = true, Score = new float[] { 1 }
                        });
                    }
                }
            }

            MLContext    mlContext = new MLContext();
            ITransformer mlModel;

            //load model if not loaded
            if (!LoadedModels.ContainsKey(config.ModelFile))
            {
                if (!System.IO.File.Exists(config.ModelFile))
                {
                    //model was not found!
                    throw new Exception($"Model not found at '{config.ModelFile}'");
                }
                else
                {
                    //add to loaded models for faster future responses
                    var model = mlContext.Model.Load(config.ModelFile, out DataViewSchema inputSchema);
                    LoadedModels.Add(config.ModelFile, model);
                    mlModel = model;
                }
            }
            else
            {
                mlModel = LoadedModels[config.ModelFile];
            }

            var prediction = mlContext.Model.CreatePredictionEngine <AIInput, AIOutput>(mlModel);
            var input      = new AIInput()
            {
                Utterance = utterance
            };

            AIOutput result = prediction.Predict(input);

            result.ExactMatch = false;

            return(result);
        }
Exemplo n.º 16
0
    protected override BTResult OnExecute(ref BTInput _input)
    {
        AIInput input = _input as AIInput;

        if (input != null)
        {
            return(input.DoAction(AIActionType.Idle));
        }


        return(BTResult.Success);
    }
Exemplo n.º 17
0
    public override void Update(AIInput input)
    {
        var ai        = input.Myself.Get <AIComponent>();
        var aircraft  = input.Myself.Get <AircraftComponent>();
        var transform = input.Myself.Get <TransformComponent>();

        if (aircraft.Armor == 0.0f)
        {
            return;
        }

        int n = frame % N;

        for (int i = 0; i < A; i++)
        {
            a[i, n] = a_[i, n];
        }
        for (int i = 0; i < S; i++)
        {
            s[i, n] = s_[i, n];
        }
        r[n] = computeReward(input);

        s[0, n] = computeState0(input);
        s[1, n] = computeState1(input);
        s[2, n] = computeState2(input);

        float q1   = (float)QNetwork.Value(s.Col(n), new VectorXd(new double[] { 0 }));
        float q2   = (float)QNetwork.Value(s.Col(n), new VectorXd(new double[] { 1 }));
        float min_ = min(q1, q2);

        q1 += -min_;
        q2 += -min_;
        if (q1 == 0 && q2 == 0)
        {
            q1 = q2 = 1;
        }

        double _a = random(new float[] { q1, q2 });

        a[0, n] = _a;

        destination    = transform.Position;
        destination.Y += _a == 0 ? 1 : -1;

        ai.AutoPilot(destination);

        if (n == N - 1)
        {
            QNetwork.Update(s, a, s_, a_, r);
        }
    }
Exemplo n.º 18
0
    public void DoSpawn_Character(bool bUpdateForce)
    {
        while (transform.childCount > 1)
        {
            DestroyImmediate(transform.GetChild(0).gameObject);
        }

        for (int i = 0; i < transform.childCount; i++)
        {
            GameObject pChildObject = transform.GetChild(0).gameObject;
            if (bUpdateForce)
            {
                DestroyImmediate(pChildObject);
            }
            else if (pChildObject.name.Contains(p_eCharacterType.ToString_GarbageSafe()) == false)
            {
                DestroyImmediate(pChildObject);
            }
        }

        if (transform.childCount == 0)
        {
            GameObject pObjectPrefab = GameObject.Instantiate(Resources.Load("Character/" + p_eCharacterType.ToString_GarbageSafe())) as GameObject;
            pObjectPrefab.transform.SetParent(transform);
            pObjectPrefab.transform.DoResetTransform();
        }

        for (int i = 0; i < listJewel.Count; i++)
        {
            listJewel[i].EventOnAwake();
        }

        AIInput pAIMovementInput = transform.GetChild(0).GetComponent <AIInput>();

        if (pAIMovementInput != null)
        {
            pAIMovementInput.DoInitJewelList(listJewel);
        }

        if (pWeapon_Equip != null)
        {
            PlayerItemCollector pCollector = transform.GetChild(0).GetComponentInChildren <PlayerItemCollector>();
            pCollector.DoCreateAndEquipWeapon(pWeapon_Equip.name);
        }

        if (pStats != null)
        {
            p_pCharacter       = transform.GetChild(0).GetComponent <CharacterModel>();
            p_pCharacter.pStat = Stats.Instantiate(pStats);
            p_pCharacter.pStat.DoInit(p_pCharacter);
        }
    }
Exemplo n.º 19
0
    public override void Update__(AIInput input)
    {
        var aircraft  = input.Myself.Get <AircraftComponent>();
        var transform = input.Myself.Get <TransformComponent>();

        if (aircraft.Armor == 0.0f)
        {
            return;
        }

        if (input.Target != null)
        {
            Vector3 destination = input.Target.Get <TransformComponent>().Position;

            // (逃げる)
            if (frame % 2400 > 1200)
            //if (false)
            {
                aircraft.Decelerate();
            }
            else
            {
                // (攻撃する)
                if (uniform(0, 1000) == 0 && aircraft.Locking)
                {
                    aircraft.Attack();
                }

                aircraft.Accelerate();
            }

            // (自動操縦)
            var p = destination * transform.Matrix.Inverse;

            if (0.2f < Vector3.Angle(new Vector3(p.X, p.Y, 0), new Vector3(0, 1, 0)))
            {
                aircraft.Roll((p.X > 0) ? 0.5f : -0.5f);
            }
            else
            {
                // 上に曲がる
                if (0.2f < abs(Vector3.Angle(p, new Vector3(0, 0, 1))))
                {
                    aircraft.Pitch(-1.0f);
                }
            }
        }
        else
        {
        }
    }
Exemplo n.º 20
0
    // Use this for initialization
    public override bool Tick(AIInput g)
    {
        g.moveHor(Player.transform.position);
        if (jumpRange != 0)
        {
            Vector3 dif = Player.transform.position - g.transform.position;
            if (Mathf.Abs(dif.x) < jumpRange && dif.y > 1)
            {
                g.jump();
            }
        }

        return(false);
    }
Exemplo n.º 21
0
    double computeReward(AIInput input)
    {
        Vector3 point;

        var collision1 = input.Myself.Get <CollisionComponent>().Shape;

        if (collision1.Velocity.Magnitude == 0)
        {
            var transform = input.Myself.Get <TransformComponent>();

            LineSegment segment = new LineSegment();
            segment.Matrix.Identity();
            segment.Matrix.Translate(transform.Position);
            segment.Direction = new Vector3(0, -300, 0);
            point             = Entity.Find("ground").Get <CollisionComponent>().Shape.Collide((AbstractShape)segment);
            if (float.IsNaN(point.X))
            {
                return(1.0f / 300.0f);
            }
            else
            {
                return(1.0f / (transform.Position - point).Magnitude);
            }
        }
        var collision2 = Entity.Find("ground").Get <CollisionComponent>().Shape;

        point = collision2.Collide(collision1);
        if (!float.IsNaN(point.X))
        {
            return(-100);
        }
        else
        {
            var transform = input.Myself.Get <TransformComponent>();

            LineSegment segment = new LineSegment();
            segment.Matrix.Identity();
            segment.Matrix.Translate(transform.Position);
            segment.Direction = new Vector3(0, -300, 0);
            point             = Entity.Find("ground").Get <CollisionComponent>().Shape.Collide((AbstractShape)segment);
            if (float.IsNaN(point.X))
            {
                return(1.0f / 300.0f);
            }
            else
            {
                return(1.0f / (transform.Position - point).Magnitude);
            }
        }
    }
Exemplo n.º 22
0
    public AINavigation(AIInput input)
    {
        _user = input.User;
        _tr = _user.transform;
        //		_seeker = _tr.gameObject.AddComponent<Seeker> ();
        //		_seeker.pathCallback += OnPathComplete;

        GameObject go = GameObject.FindGameObjectWithTag("Player");

        if(go == null)
            Debug.LogError("Could not find the player");
        target = go.transform;

        //		_user.StartCoroutine (RepeatTrySearchPath ());
    }
Exemplo n.º 23
0
    /// <summary>
    /// Select a child to run based on the policy.
    /// </summary>
    /// <param name="tank">Tank being controlled</param>
    /// <returns>Child to run, or null if no runnable children.</returns>
    private BehaviorTreeNode SelectChild(AIInput g)
    {
        switch (Policy)
        {
        case SelectionPolicy.Prioritized:

            for (int i = 0; i < Children.Count; i++)
            {
                BehaviorTreeNode child = Children[i];
                //Debug.Log(child +" - "+i);
                if (selected == child)
                {
                    return(child);
                }
                if (child.Decide(g))
                {
                    return(child);
                }
            }
            //Debug.Log("none");
            return(null);

        case SelectionPolicy.Sequential:

            for (int i = 0; i < Children.Count; i++)
            {
                int j = (i + sequentialChild) % Children.Count;
                BehaviorTreeNode child = Children[j];
                //Debug.Log(child +" - "+i);
                if (selected == child)
                {
                    return(child);
                }
                if (child.Decide(g))
                {
                    sequentialChild = j;
                    return(child);
                }
            }
            //Debug.Log("none");
            return(null);

        default:
            throw new NotImplementedException("Unimplemented policy: " + Policy);
        }
    }
Exemplo n.º 24
0
    public override bool Tick(AIInput g)
    {
        Vector3 selected;

        if (!g.point)
        {
            return(false);
        }

        selected = g.point.transform.position;
        //Debug.Log(selected);
        g.move(selected);
        if ((g.transform.position - selected).magnitude <= range)
        {
            return(false);
        }
        return(true);
    }
Exemplo n.º 25
0
    double computeState2(AIInput input)
    {
        var transform = input.Myself.Get <TransformComponent>();

        LineSegment segment = new LineSegment();

        segment.Matrix.Identity();
        segment.Matrix.Translate(transform.Position);
        segment.Direction = new Vector3(0, -300, 0);
        var point = Entity.Find("ground").Get <CollisionComponent>().Shape.Collide((AbstractShape)segment);

        if (float.IsNaN(point.X))
        {
            return(300);
        }
        else
        {
            return((transform.Position - point).Magnitude);
        }
    }
Exemplo n.º 26
0
        public override void OnAwake(bool notify = true)
        {
            base.OnAwake(notify);


            aiInput = instance.GetComponentInChildren <AIInput>();
            if (aiInput == null)
            {
                Debug.LogWarning("AIInput is expected in the prefab");
                return;
            }
            pc2d      = instance.GetComponentInChildren <PlatformerCollider2D>();
            character = instance.GetComponentInChildren <Character>();


            aiInput.SetX(1);
            character.onAreaChange  += OnAreaChange;
            character.onStateChange += OnStateChange;
            pc2d.onLeftWall         += OnLeftWall;
            pc2d.onRightWall        += OnRightWall;
        }
Exemplo n.º 27
0
        public Human(Vector2 spawnPosition, Texture2D texture, List <Entity> obstacles, int team)
        {
            animationFactory = new AnimationFactory();
            Position         = spawnPosition;
            Texture          = texture;
            Team             = team;
            Scale            = 1f;
            Input            = new AIInput();
            _PhysicsHandler  = new PhysicsHandler();
            List <ICollision> collidableList = new List <ICollision>();

            foreach (var obstacle in obstacles)
            {
                if (obstacle._collision != null)
                {
                    collidableList.Add(obstacle._collision);
                }
            }
            _collision                = new HumanCollision(spawnPosition, collidableList);
            _collision.Parent         = this;
            healthBar                 = new HealthBar();
            healthBar.ParentTransform = this;
            healthBar.Health          = this;
        }
Exemplo n.º 28
0
 public override bool Tick(AIInput g)
 {
     g.move(Player.transform.position);
     g.shoot();
     return(false);
 }
Exemplo n.º 29
0
 // Use this for initialization
 void Start()
 {
     ai = GetComponent <AIInput>();
 }
Exemplo n.º 30
0
 public override void Activate(AIInput g)
 {
     g.wait(waitTime);
     //Debug.Log(arrivalTime+ "here");
 }
Exemplo n.º 31
0
 public override void Activate(AIInput g)
 {
     g.pickPoint();
     //Debug.Log(arrivalTime+ "here");
 }