Inheritance: MonoBehaviour
    void Start()
    {
        LockstepManager.Initialize ();
        GridManager.Generate ();
        const int count = 32;

        for (int i = -count; i < count; i++)
        {
            for (int j = -count; j < count; j++)
            {
                if (i * i + j * j < 16) continue;
                if (LSUtility.GetRandom (2) == 0)
                {
                    Vector2d pos = new Vector2d(i,j);
                    GridManager.GetNode(pos.x,pos.y).Unwalkable = true;
                    Instantiate(TestWall).GetComponent<LSBody>().Initialize(pos);
                }
            }
        }

        /*LSBody wall = Instantiate (TestWall).GetComponent<LSBody> ();
        wall.Initialize (new Vector2d (-32 + 14, 0));
        for (long i = wall.XMin; i <= wall.XMax; i+= FixedMath.One) {
            for (long j = wall.YMin; j <= wall.YMax; j+= FixedMath.One) {
                GridManager.GetNode (i, j).Unwalkable = true;
            }
        }*/

        GridManager.Initialize ();
        controller = AgentController.Create ();
        for (int i = 0; i < 256; i++) {
            agent = controller.CreateAgent (AgentCode.Minion);
        }
        PlayerManager.AddAgentController (controller);
    }
 protected override void OnStartGame()
 {
     for (int i = 0; i < _spawnAmount; i++) {
         AgentController ac = new AgentController();
         PlayerManager.AddController (ac);
         ac.CreateAgent (_spawnCode,Vector2d.zero);
     }
 }
        public void GivenACallAction_WhenStatusIsCompleted_ThenResponseWillBeEmpty()
        {
            var controller = new AgentController();
            var result = controller.Call("1", "completed");

            result.ExecuteResult(MockControllerContext.Object);

            Assert.That(Result.ToString(), Is.Empty);
        }
 public static AgentController CreateAgentController()
 {
     if (_AgentController == null)
     {
         var clientsProcessor = CreateClientsProcessor();
         var disconnectedClientProccessor = CreateDisconnectedClientProccessor(clientsProcessor);
         var commandTransfer = CreateCommandTransfer(clientsProcessor);
         _AgentController=new AgentController(clientsProcessor, commandTransfer, disconnectedClientProccessor);
     }
     return _AgentController;
 }
        public void GivenAConnectMessage_ThenRespondsWithInstructions()
        {
            var controller = new AgentController();
            var result = controller.ConnectMessage();

            result.ExecuteResult(MockControllerContext.Object);

            var document = LoadXml(Result.ToString());

            Assert.That(document.SelectSingleNode("Response/Say"), Is.Not.Null);
        }
        protected internal virtual AgentControllerInterface createAgent(Props agentProps)
        {
            AgentController controller = null;
            string classname = agentProps.getString("classname");
            if (classname.Length > 0)
            {
                if (classname.Equals("com.neokernel.xml.XMLStartupAgent"))
                {
                    classname = "Feng.NeoKernel.nk.LicenseFreeXMLStartupAgent";
                }

                if (!classname.Equals("com.neokernel.xml.XMLStartupAgent") && !classname.Equals("com.neokernel.nk.Trmntr"))
                {
                    this.println("Creating agent " + classname);
                }
                try
                {
                    AgentInterface agent = null;
                    IClassFactoryInterface defaultClassFactory = (IClassFactoryInterface) agentProps.getProperty("class_factory");
                    if (defaultClassFactory == null)
                    {
                        defaultClassFactory = NK.DefaultClassFactory;
                    }
                    agent = (AgentInterface) defaultClassFactory.createInstance(classname);
                    Type type = agent.GetType();
                    if (!agentProps.hasProperty("name"))
                    {
                        string fullName = type.FullName;
                        int num = fullName.LastIndexOf('.');
                        if (num > 0)
                        {
                            fullName = fullName.Substring(num + 1);
                        }
                        agentProps.setProperty("name", fullName);
                    }
                    agentProps.setDefault("agent_id", this.NextAgentID);
                    agent.Props = agentProps;
                    controller = new AgentController(agent);
                }
                catch (ArgumentException exception)
                {
                    this.error("Could not create Agent: " + classname, exception);
                }
                catch (ClassFactoryException exception2)
                {
                    this.error("Could not create Agent: " + classname, exception2);
                }
            }
            return controller;
        }
        public void GivenACallAction_WhenStatusIsDifferentThanCompleted_ThenRecordTheCallAndHangup()
        {
            var controller = new AgentController {Url = Url};
            var result = controller.Call("1", "busy");

            result.ExecuteResult(MockControllerContext.Object);

            var document = LoadXml(Result.ToString());

            Assert.That(document.SelectSingleNode("Response/Record").Attributes["action"].Value,
                Is.EqualTo("/Agent/Hangup"));
            Assert.That(document.SelectSingleNode("Response/Record").Attributes["transcribeCallback"].Value,
                Is.EqualTo("/Recording/Create?agentId=1"));
            Assert.That(document.SelectSingleNode("Response/Hangup"), Is.Not.Null);
        }
Exemple #8
0
    void Start()
    {
        agentController = GetComponent <AgentController>();
        utils           = GetComponent <AgentUtils>();
        config          = agentController.config;

        sideVector = utils.sideVector;
        ball       = GameObject.Find("Ball").transform;
        agentController.otherGoal.GetComponent <Goal>().scoreEvent.AddListener(AddPositiveReward);
        agentController.goal.GetComponent <Goal>().scoreEvent.AddListener(AddNegativeReward);

        fieldSize = utils.floor.lossyScale;

        currentTargetPosition = Vector3.zero;

        currentBallRegion = ball.position;

        RequestDecision();
    }
Exemple #9
0
    void OnTriggerEnter(Collider c)
    {
        if (!soldOut && c.gameObject.tag == "Player")
        {
            AgentController player = c.gameObject.GetComponent <AgentController>();

            if (player.money >= item.price)
            {
                // subtract money and add item
                player.money -= item.price;
                player.items.Add(item);

                // apply effects
                if (item.setRatKing)
                {
                    player.ratKing = true;
                }
                player.health += item.healthIncrease;
                player.reach  += item.rangeIncrease;
                if (item.fireRateIncrease != 0)
                {
                    player.fireRate /= item.fireRateIncrease;
                }
                player.agent.speed     += item.speedIncrease;
                player.moneyMultiplier += item.moneyMultiplierIncrease;

                // refresh items
                foreach (GameObject o in GameObject.FindGameObjectsWithTag("UIitem"))
                {
                    Destroy(o);
                }
                foreach (GameObject o in GameObject.FindGameObjectsWithTag("UIcamera"))
                {
                    o.GetComponent <UIController>().updateItems();
                }

                // remove item from shop
                soldOut              = true;
                displayText.text     = "SOLD OUT";
                displaySprite.sprite = null;
            }
        }
    }
Exemple #10
0
    // Use this for initialization
    public override void Start()
    {
        //Call base to load awareness controller
        base.Start();
        _agentController = GetComponentInParent <AgentController>();
        if (transform.parent.CompareTag("Agent"))
        {
            isAgentChild = true;
        }
        else
        {
            isAgentChild = false;
        }

        if (isAgentChild)
        {
            rotationTracker = 0;
        }
    }
Exemple #11
0
        public void LoadData()
        {
            List <tbl_Agent> a = new List <tbl_Agent>();

            if (Request.QueryString["s"] != null)
            {
                string s = Request.QueryString["s"];
                //txtAgentName.Text = s;
                a = AgentController.GetAll(s);
            }
            else
            {
                a = AgentController.GetAll("");
            }
            if (a.Count > 0)
            {
                pagingall(a);
            }
        }
Exemple #12
0
    private void Start()
    {
        spawnPosition = transform.position;
        spawnRotation = transform.rotation;
        ResetAgentCheckPoints();
        minimapMarker.SetActive(true);
        weaponController = GetComponent <WeaponController>();

        rb = GetComponent <Rigidbody>();
        rb.maxAngularVelocity = Mathf.Infinity;
        rb.drag   = drag;
        dragDelta = dragMax - drag;
        mass      = rb.mass;

        // Вычисляем расстояние от центра координат машины до земли
        Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, Mathf.Infinity, surfaceSearchMask);
        distanceToGround = transform.position - hit.point;

        // Создаем Healthbar
        if (healthBar != null)
        {
            healthBar.CreateHealthbar(hp);
        }
        else
        {
            Debug.Log(playerName + ": Healthbar not found");
        }

        currentHp = hp;

        if (!isAgent)
        {
            controls.Player.Respawn.performed  += _ => Respawn();
            controls.Player.Jump.performed     += _ => Jump();
            controls.Player.Fire.performed     += _ => weaponController.Fire();
            controls.Player.LandMine.performed += _ => weaponController.SetMine();
            enabled = false;
        }
        else
        {
            agent = GetComponent <AgentController>();
        }
    }
Exemple #13
0
        public void MoveFinish()
        {
            Vector3Int currentCell = MapIns.WorldToCell(transform.position).ZToZero();

            if (!Remote.Binding())
            {
                if (MapIns.GetNearestPosition(currentCell, out Vector3Int result))
                {
                    // StartMove(currentCell, result); // main thread
                    // AsyncStartMove(currentCell, result); // another thread
                    AgentController.MoveAgent(this, currentCell, result, currentEnemy);
                    curMoveStep = 0;
                }
            }
            else
            {
                Stop();
            }
        }
Exemple #14
0
    bool GetClosestEnemy()
    {
        Collider[] objects = Physics.OverlapSphere(transform.position, RangeToFindEnemy);

        if (objects.Length > 0)
        {
            GameObject closestEnemy    = null;
            float      closestDistance = 0;
            foreach (Collider col in objects)
            {
                if (col.tag == "Player")
                {
                    AgentController control = col.GetComponent <AgentController>();
                    if (control == null)
                    {
                        continue;
                    }
                    if (control.Team == Team)
                    {
                        continue;
                    }
                    Debug.Log("musuh ni");
                    float dist = Vector3.Distance(col.gameObject.transform.position, transform.position);
                    if (closestDistance < dist)
                    {
                        closestEnemy    = col.gameObject;
                        closestDistance = dist;
                    }
                }
            }
            nearestEnemy = closestEnemy;
            if (nearestEnemy != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        return(false);
    }
        public void GenerateProcessorAgents()
        {
            String index;

            dispCont  = JadeHelper.CreateContainer("DispatcherContainer", false, "localhost", null, "1150");
            dispAgent = JadeHelper.CreateAgent(dispCont, "DispatcherAgent", "Project_MASMA.DispatcherAgent", null);

            for (int i = 0; i < Constants.ProcessorNumber; i++)
            {
                index = (i < 9) ? "0" + i : i.ToString();
                procCont.Add(JadeHelper.CreateContainer("container" + i, false, "localhost", null, "11" + index));
                procAgents.Add(JadeHelper.CreateAgent(procCont[i], "ProcessorAgent" + i, "Project_MASMA.ProcessorAgent", null));
            }
            dispAgent.start();
            for (int i = 0; i < Constants.ProcessorNumber; i++)
            {
                procCont[i].start();
                procAgents[i].start();
            }
        }
Exemple #16
0
    public void AddControl(ControlType controlType)
    {
        switch (controlType)
        {
        case ControlType.Human:
            agentController = new HumanAgentController(gameObject);
            break;

        case ControlType.Random:
            agentController = new RandomAgentController();
            break;

        case ControlType.ForwardBack:
            agentController = new MacroFBAgentController();
            break;

        default:
            throw new System.Exception("Invalid control type");
        }
    }
Exemple #17
0
    public void DisplayText(string text, AgentController agent)
    {
        if (agent is AndroidController)
        {
            AndroidController android = (AndroidController)agent;
            androidText.text = text;
            androidPanel.gameObject.SetActive(true);

            if (!actives.ContainsKey(android.Head))
            {
                actives.Add(android.Head, androidPanel.gameObject);
            }
        }
        else
        {
            PlayerController player = (PlayerController)agent;
            playerText.text = text;
            playerPanel.gameObject.SetActive(true);
        }
    }
Exemple #18
0
    private void OnCollisionEnter(Collision collision)
    {
        if (capacity <= harvestedFood)
        {
            return;
        }

        if (collision.transform.CompareTag("food"))
        {
            harvestedFood++;
            AgentController.EatFood(agent, collision.gameObject, agent.arena);
            agent.agentKnowledge.observedFoods.Remove(collision.gameObject);
        }
        if (collision.transform.CompareTag("badFood"))
        {
            harvestedFood++;
            AgentController.EatBadFood(agent, collision.gameObject, agent.arena);
            agent.agentKnowledge.observedFoods.Remove(collision.gameObject);
        }
    }
Exemple #19
0
    private void OnCollisionEnter(Collision collision)
    {
        if (bossCtrl == null || (bossCtrl != null && !bossCtrl.IsSetuppedAndEnabled()))
        {
            return;
        }

        if (collision.gameObject.layer == LayerMask.NameToLayer("Obstacle"))
        {
            OnObstacleHit?.Invoke(collision.gameObject);
        }
        else
        {
            AgentController agent = collision.gameObject.GetComponent <AgentController>();
            if (agent != null)
            {
                OnAgentHit?.Invoke(agent);
            }
        }
    }
        // Update is called once per frame
        public override void OnStateUpdate()
        {
            AgentController agentController = cachedAgentController;

            _Timer -= Time.deltaTime;

            if (_Timer <= 0.0f)
            {
                if (agentController != null)
                {
                    OnUpdateAgent();
                }
                _Timer = Random.Range(_MinInterval, _MaxInterval);
            }

            if (agentController != null && agentController.isDone)
            {
                OnDone();
            }
        }
    public virtual void OnAttacked(AgentController attacker)
    {
        if (attacker.team == team)
        {
            return;
        }

        health -= attacker.GetComponentInChildren <Weapon>().damage;

        if (health < 0)
        {
            health = 0f;
            OnDie(attacker);
            // die animation
        }
        else
        {
            // damage animation
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        agentController = GetComponent <AgentController>();
        config          = agentController.config;
        ball            = GameObject.Find("Ball").transform;
        floor           = GameObject.Find("Floor").transform;

        teammates = new List <Transform>();
        opponents = new List <Transform>();

        sideVector = (agentController.isLeftSide)?new Vector3(1, 0f, 1):new Vector3(-1, 0f, -1);

        foreach (GameObject obj in GameObject.FindGameObjectsWithTag("left"))
        {
            if (obj != gameObject)
            {
                if (agentController.isLeftSide)
                {
                    teammates.Add(obj.transform);
                }
                else
                {
                    opponents.Add(obj.transform);
                }
            }
        }
        foreach (GameObject obj in GameObject.FindGameObjectsWithTag("right"))
        {
            if (obj != gameObject)
            {
                if (!agentController.isLeftSide)
                {
                    teammates.Add(obj.transform);
                }
                else
                {
                    opponents.Add(obj.transform);
                }
            }
        }
    }
Exemple #23
0
    public override void EnterState(GameObject agent)
    {
        if (agent.tag == Constants.MinionTag)
        {
            Debug.Log("Enter Attack State");
        }

        AgentController controller = agent.GetComponent <AgentController>();

        //Get target from sensor
        SetNextTarget(agent, controller);

        Animator anim = agent.GetComponent <Animator>();

        anim.SetBool("hasTargetInRange", true);

        //NavMeshAgent navAgent = agent.GetComponent<NavMeshAgent>();
        //if (navAgent == null)
        //    return;
        //navAgent.enabled = false;
    }
Exemple #24
0
    public AgentState(GameObject gameObject) : base(gameObject)
    {
        self           = gameObject.GetComponent <Agent>();
        agentStats     = self.agentStats;
        controller     = gameObject.GetComponent <AgentController>();
        groundLayer    = self.groundLayer;
        charController = gameObject.GetComponent <CharacterController>();
        weapons        = gameObject.GetComponent <AgentWeapons>();
        health         = gameObject.GetComponent <AgentHealth>();
        stamina        = gameObject.GetComponent <AgentStamina>();
        vigor          = gameObject.GetComponent <AgentVigor>();
        anim           = gameObject.GetComponentInChildren <Animator>();
        audioManager   = AudioManager.instance;
        poolManager    = PoolManager.Instance;
        animEvents     = gameObject.GetComponentInChildren <AgentAnimEvents>();
        navAgent       = gameObject.GetComponent <NavMeshAgent>();
        audio          = gameObject.GetComponentInChildren <AudioSource>();

        transitionsTo.Add(new Transition(typeof(Dying), IsDead));
        transitionsTo.Add(new Transition(typeof(TakingDamage), () => health.TookSignificatDamage));
    }
    void Start()
    {
        LockstepManager.Initialize();
        GridManager.Generate();
        const int count = 32;


        for (int i = -count; i < count; i++)
        {
            for (int j = -count; j < count; j++)
            {
                if (i * i + j * j < 16)
                {
                    continue;
                }
                if (LSUtility.GetRandom(2) == 0)
                {
                    Vector2d pos = new Vector2d(i, j);
                    GridManager.GetNode(pos.x, pos.y).Unwalkable = true;
                    Instantiate(TestWall).GetComponent <LSBody>().Initialize(pos);
                }
            }
        }

        /*LSBody wall = Instantiate (TestWall).GetComponent<LSBody> ();
         * wall.Initialize (new Vector2d (-32 + 14, 0));
         * for (long i = wall.XMin; i <= wall.XMax; i+= FixedMath.One) {
         *      for (long j = wall.YMin; j <= wall.YMax; j+= FixedMath.One) {
         *              GridManager.GetNode (i, j).Unwalkable = true;
         *      }
         * }*/

        GridManager.Initialize();
        controller = AgentController.Create();
        for (int i = 0; i < 256; i++)
        {
            agent = controller.CreateAgent(AgentCode.Minion);
        }
        PlayerManager.AddAgentController(controller);
    }
Exemple #26
0
 // Use this for initialization
 protected override void Start()
 {
     base.Start();
     _agent             = GetComponent <AgentController> ();
     _agent.CurrentTask = this;
     _memory            = GetComponent <Memory> ();
     _moving            = GetComponent <Moving> ();
     _inventory         = GetComponent <Inventory>();
     _village           = GameObject.Find("Village").GetComponent <Village>();
     _construction      = _village.GetPrefab("ConstructionSite");
     _target            = null;
     _stockpile         = null;
     _buildingDecision  = new DecisionTree <GameObject>();
     System.Reflection.MethodInfo[] methods = this.GetType().GetMethods();
     foreach (YamlLoader.PropertyElement element in (List <YamlLoader.PropertyElement>)Manager.Instance.Properties.GetElement("BuildingCost").Value)
     {
         _buildingDecision.AddAction(new DecisionTree <GameObject> .Action(element.Name, _village.GetPrefab(element.Name)));
     }
     foreach (System.Reflection.MethodInfo method in methods)
     {
         if (((BuildingChoiceMethod[])method.GetCustomAttributes(typeof(BuildingChoiceMethod), true)).Length > 0)
         {
             List <DecisionTree <GameObject> .Action> actions = new List <DecisionTree <GameObject> .Action>();
             List <float> weights = new List <float>();
             foreach (BuildingChoiceLink link in (BuildingChoiceLink[])method.GetCustomAttributes(typeof(BuildingChoiceLink), true))
             {
                 DecisionTree <GameObject> .Action a = _buildingDecision.GetAction(link.Name);
                 if (a != null)
                 {
                     actions.Add(a);
                     weights.Add(link.Weight);
                 }
             }
             if (actions.Count > 0)
             {
                 _buildingDecision.AddPercept(new DecisionTree <GameObject> .Percept(method.Name, actions.ToArray(), weights.ToArray()));
             }
         }
     }
 }
    public void SpeakText(AgentController currentAgent, string text)
    {
        textToSpeak  = "<speak version=\"1.0\">";
        textToSpeak += "<voice-transformation type=\"Custom\" pitch=\" " + sp_pitch
                       + " % \" pitch_range =\"" + sp_pitchRange
                       + " % \" rate =\"" + sp_rate
                       + " % \" breathiness =\"" + sp_breathiness
                       + " % \" glottal_tension =\" " + sp_glottalTension
                       + " % \" >";
        currentPlainTalkText = "";

        textToSpeak          += text;
        currentPlainTalkText += text;

        AgentGender gender = currentAgent.agentGender;

        if (OnlySaveToWav)
        {
            gender = saveGenders[saveIndex];
        }

        if (_synthesizePlayed)
        {
            _synthesizePlayed = false;

            textToSpeak += "</voice-transformation>" + "</speak>"; // finalize
            if (OnlySaveToWav)
            {
                Debug.Log("Saving to: " + saveNames[saveIndex] + ", " + textToSpeak);
            }
            else
            {
                Debug.Log("Saying:" + textToSpeak);
            }

            agentToTalkNewIK = currentAgent;

            Runnable.Run(CallSpeakService(gender));
        }
    }
Exemple #28
0
        public async Task GiveAgentsAddingTargets_WhenGetAssignments_CorrectTargetsShouldBeReturned()
        {
            // Arrange
            IWatcherRepository watcherRepository = new CosmosWatcherRepository(_watcherOption, _loggerFactory);
            await watcherRepository.Database.Delete(_databaseName, CancellationToken.None);

            await watcherRepository.InitializeContainers();

            IRecordContainer <TargetRecord> targetContainer = await watcherRepository.Container.Create <TargetRecord>();

            targetContainer.Should().NotBeNull();

            IAgentController agentController = new AgentController(_watcherOption, watcherRepository, _loggerFactory.CreateLogger <AgentController>());

            // Act
            const int max    = 10;
            var       agents = new List <AgentRecord>();

            foreach (int targetCount in Enumerable.Range(1, max))
            {
                await targetContainer.CreateTestTarget(targetCount);
            }

            foreach (int agentCount in Enumerable.Range(1, max))
            {
                agents.Add(await agentController.CreateTestAgent(agentCount));

                foreach (var agent in agents)
                {
                    await agentController.LoadBalanceAssignments();

                    IReadOnlyList <TargetRecord> assignments = await targetContainer.GetAssignments(agent.Id, _loggerFactory.CreateLogger <TargetRecord>());

                    assignments.Count.Should().BeGreaterThan(0);
                }
            }

            // Clean up
            await watcherRepository.Database.Delete(_databaseName, CancellationToken.None);
        }
Exemple #29
0
    private bool ExplodeCell(Vector3Int relativePos, BombConfig bombConfig, AgentController bomber, bool isFirstRow = false)
    {
        Vector3 pos = tilemap.GetCellCenterWorld(relativePos);

        Tile tile = tilemap.GetTile <Tile>(relativePos);

        if (tile == wallTile)
        {
            return(false);
        }
        Collider2D collider = Physics2D.OverlapPoint(pos, LayerMask.GetMask("Bomb"));

        if (collider != null && !isFirstRow)
        {
            if (collider.tag == "Bomb")
            {
                collider.gameObject.GetComponent <Bomb>().SetCountdown(bombConfig.timeBeteweenExplosions);
            }
            return(false);
        }


        GameObject newExplosion = GetExplosion(pos);

        // mapController.AddNewExplosionToMap(cellPos, bomber);
        gameController.AddExplosion(newExplosion, relativePos, bomber);

        if (tile == destructibleTile)
        {
            tilemap.SetTile(relativePos, null);
            //mapController.CreateNewItem(cellPos);
            //newExplosion.GetComponent<Explosion>().SetConfigs(mapController, cellPos, true);
            return(false);
        }

        //newExplosion.GetComponent<Explosion>().SetConfigs(mapController, cellPos);

        return(true);
    }
Exemple #30
0
    public void Explode(Vector2 worldPos, BombType bomb, AgentController bomber)
    {
        //int initialMatchId = gameController.matchId;
        Vector3Int originCell = tilemap.WorldToCell(worldPos);
        BombConfig bombConfig = AllEnviromentCommon.Instance.GetBombConfigs(bomb);
        int        radius     = bombConfig.radius;

        ExplodeCell(originCell, bombConfig, bomber, true);
        foreach (var direction in directions)
        {
            for (int i = 1; i < radius + 1; i++)
            {
                /*if (initialMatchId != gameController.matchId) {
                 *  return;
                 * }*/
                if (!ExplodeCell(originCell + i * direction, bombConfig, bomber))
                {
                    break;
                }
            }
        }
    }
Exemple #31
0
    // Update is called once per frame
    private void Update()
    {
        if (enable)
        {
            Vector3    nextLaserPoint;
            float      checkAgentDistance = maxLaserRange;
            RaycastHit hit;

            //Controllo se colpisco un ostacolo
            if (Physics.SphereCast(transform.position, laserRadius, transform.forward, out hit, maxLaserRange, laserColliderLayer))
            {
                if (hit.collider)
                {
                    nextLaserPoint     = hit.point;
                    checkAgentDistance = hit.distance;
                }
                else
                {
                    nextLaserPoint = transform.position + (transform.forward * maxLaserRange);
                }
            }
            else
            {
                nextLaserPoint = transform.position + (transform.forward * maxLaserRange);
            }

            //Controllo se colpisco un agent al max range dell'ostacolo
            if (Physics.SphereCast(transform.position, laserRadius, transform.forward, out hit, checkAgentDistance, agentLayer))
            {
                AgentController agent = hit.transform.gameObject.GetComponent <AgentController>();
                if (agent != null)
                {
                    OnAgentHit?.Invoke(agent);
                }
            }

            lineRenderer.SetPosition(1, nextLaserPoint);
        }
    }
Exemple #32
0
    // Use this for initialization
    private void Start()
    {
        _agent = GetComponent <AgentController>();
        _db    = new Database();
        _db.Add("Patch", new Database.Table(new string[]
        {
            "Type", "Above", "PosX", "PosZ", "LastUpdate"
        }, new Type[]
        {
            typeof(bool), typeof(string), typeof(int), typeof(int), typeof(float)
        }));
        int mapWidth  = Manager.Instance.GetComponent <Manager>().Width;
        int mapHeight = Manager.Instance.GetComponent <Manager>().Height;

        Database.Table t = _db.Tables["Patch"];
        foreach (Patch patch in GameObject.Find("Ground").GetComponentsInChildren <Patch>())
        {
            t.Insert(new object[] {
                patch.name == "Grass(Clone)", "None", (int)patch.transform.position.x, (int)patch.transform.position.z, 0f
            });
        }
    }
    IEnumerator stats()
    {
        yield return(new WaitForSeconds(10.0f));

        float speed              = 0;
        int   agentsDied         = 0;
        int   agentsBorn         = 0;
        int   agentsInGeneration = FindObjectsOfType <AgentController>().Length;

        Debug.Log("GENERATION: " + generation);
        Debug.Log("Agents alive: " + agentsInGeneration);
        foreach (AgentController agent in FindObjectsOfType <AgentController>())
        {
            AgentController agentController = agent.GetComponent <AgentController>();
            speed += agentController.speed;
            if (agentController.food == 0)
            {
                agentController.die();
                agentsDied++;
            }
            else if (agentController.food >= 2)
            {
                agentController.reproduce();
                agentController.food   = 0;
                agentController.energy = agentController.initialEnergy;
                agentsBorn++;
            }
            else
            {
                agentController.food   = 0;
                agentController.energy = agentController.initialEnergy;
            }
        }
        Debug.Log("Agents born: " + agentsBorn);
        Debug.Log("Agents dead: " + agentsDied);
        Debug.Log("Speed avg: " + (speed / (agentsInGeneration * 1.0f)));
        generation++;
        StartCoroutine(stats());
    }
Exemple #34
0
 void FixedUpdate()
 {
     SetLineRenderer();
     if (canCharge && target != null)
     {
         SetEnergySize();
         if (energy > 0)
         {
             target.energyPower += Time.deltaTime * 2;
             energy             -= Time.deltaTime * 2;
             target.SetSize();
             if (target.energyPower > 150)
             {
                 target = null;
             }
         }
         else
         {
             GetEnergy();
         }
     }
 }
    public override IEnumerator Apply(ITriggerAgent agent)
    {
        var             lowestTTC    = TimeToCollisionLimit;
        var             egos         = SimulatorManager.Instance.AgentManager.ActiveAgents;
        AgentController collisionEgo = null;

        foreach (var ego in egos)
        {
            var agentController = ego.AgentGO.GetComponentInChildren <AgentController>();
            var ttc             = CalculateTTC(agentController, agent);
            if (ttc >= lowestTTC || ttc < 0.0f)
            {
                continue;
            }

            lowestTTC    = ttc;
            collisionEgo = agentController;
        }

        //If there is no collision detected don't wait
        if (lowestTTC >= TimeToCollisionLimit || collisionEgo == null)
        {
            yield break;
        }

        //Agent will adjust waiting time while waiting
        do
        {
            yield return(null);

            lowestTTC = CalculateTTC(collisionEgo, agent);
            //Check if TTC is valid, for example ego did not change the direction
            if (lowestTTC >= TimeToCollisionLimit)
            {
                yield break;
            }
        } while (lowestTTC > 0.0f);
    }
Exemple #36
0
    public AgentController Spawn(Vector3 pos, City city = null)
    {
        if (city == null)
        {
            city = wc.Town;
        }

        GameObject go = Instantiate(agent_template, pos, Quaternion.identity, wc.AgentRealm);

        go.name = "Agent" + spawnerCounter++.ToString();
        AgentController ac = go.transform.GetComponent <AgentController>();

        ac.City = city;

        city.KeepTrack(ac);

        if (pos == Vector3.zero)
        {
            go.transform.position = ac.City.RandomPos;
        }

        return(ac);
    }
Exemple #37
0
 private IEnumerator CampCo()
 {
     logger.LogFormat(LogType.Log, "{0} co init...", LogTag);
     while (_alive)
     {
         if (boss == null)
         {
             _alive = false;
             foreach (Transform c in transform)
             {
                 AgentController ac = c.GetComponent <AgentController>();
                 ac.OnDie(ac);
             }
         }
         else if (transform.childCount < campCapacity)
         {
             CreateDragon();
         }
         yield return(new WaitForSeconds(coInterval));
     }
     logger.LogFormat(LogType.Log, "{0} co end...", LogTag);
     Destroy(this);
 }
Exemple #38
0
 public IdleState(AgentController agentCtrl)
 {
     agent = agentCtrl;
 }
        public void GivenAScreenCallAction_ThenResponseContainsSpelledPhoneNumber()
        {
            var controller = new AgentController {Url = Url};
            var result = controller.ScreenCall("1234567890");

            result.ExecuteResult(MockControllerContext.Object);

            StringAssert.Contains("1, 2, 3, 4, 5, 6, 7, 8, 9, 0", Result.ToString());
        }
Exemple #40
0
 public FearState(AgentController agentCtrl)
 {
     agent = agentCtrl;
 }
Exemple #41
0
 public HuntState(AgentController agentCtrl)
 {
     agent = agentCtrl;
 }
Exemple #42
0
 public void Update()
 {
     Instance = this;
     HandleDragging();
 }
Exemple #43
0
 public void Start()
 {
     Instance = this;
     tools = new[] { new NavigationTool() };
     currentTool = tools[0];
 }
Exemple #44
0
 public CounterState(AgentController agentCtrl)
 {
     agent = agentCtrl;
 }
        public void GivenAScreenCallAction_ThenResponseContainsGatherAndHangup()
        {
            var controller = new AgentController{Url = Url};
            var result = controller.ScreenCall("1234567890");

            result.ExecuteResult(MockControllerContext.Object);

            var document = LoadXml(Result.ToString());

            Assert.That(document.SelectSingleNode("Response/Gather").Attributes["action"].Value,
                Is.EqualTo("/Agent/ConnectMessage"));
            Assert.That(document.SelectSingleNode("Response/Hangup"), Is.Not.Null);
        }
        private static AgentController GetAgentController(IAgentRepository repository)
        {
            var controller = new AgentController(repository);

            controller.ControllerContext = new ControllerContext()
            {
                Controller = controller,
                RequestContext = new RequestContext(new MockHttpContext(), new RouteData())
            };
            return controller;
        }
Exemple #47
0
 public EngageState(AgentController agentCtrl)
 {
     agent = agentCtrl;
 }