Esempio n. 1
0
    void Update()
    {
        // Always invoke basic state.
        this.basicState.update(gameObject);

        // No behavior?
        if (currentState != null)
        {
            IAState next = this.currentState.update(gameObject);

            // This state was finished?
            if (next == null)
            {
                finishCurrentState();
            }
            else if (next != this.currentState)
            {
                // The state was updated?
                // Then use the new state, and add to List
                setCurrentState(next);
            }
        }


        //        Debug.Log("Alive?" + attributes.isAlive().GetValueOrDefault(true));

        if (!attributes.isAlive().GetValueOrDefault(true))
        {
            currentState = null;
            // Object was killed.
            //            gameObject.Send<IAnimalAnimatorHelper>((_ => _.die()));
        }
    }
Esempio n. 2
0
    public void setCurrentState(IAState next)
    {
        IAState previous = null;

        if (next == null)
        {
            this.currentState = null;
            return;
        }

        // same state, ignore
        if (this.currentState != null && next.getCod() == this.currentState.getCod())
        {
            return;
        }

        if (states.Count >= MAX_MEM_STATES)
        {
            states.Remove(states[0]);
        }

        if (this.currentState != null)
        {
            states.Add(this.currentState);
            previous = this.currentState;
        }

        this.currentState = next;
        this.currentState.setPrevious(previous);

        // Initialize the state.
        this.currentState.start(gameObject);
    }
Esempio n. 3
0
    void Update()
    {
        navMesh.destination = player.transform.position;


        if (navMesh.isStopped)
        {
            State = IAState.Attacking;
        }
        else
        {
            State = IAState.Walking;
        }

        if (State == IAState.Attacking)
        {
            bloodPlayer.blood = bloodPlayer.blood - damage * Time.deltaTime;
        }

        AnimationControl.SetFloat("velocidade", navMesh.velocity.magnitude);


        if (blood.blood <= 0)
        {
            {
                Destroy(gameObject);
            }
        }
    }
Esempio n. 4
0
    void FixedUpdate()
    {
        lineOfSight.enabled = _config.lightIsOn;
        lineOfSight.SetStatus(LineOfSight.Status.Idle);

        if (lineOfSight.enabled)
        {
            if (lineOfSight.SeeByTag("Player"))
            {
                List <GameObject> obs    = lineOfSight.getViewing();
                GameObject        obj    = obs[0];
                Player            player = obj.GetComponent <Player>();

                if (player != null)
                {
                    if (!player.disguised)
                    {
                        Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, alertRadious);

                        GameObject nearest     = null;
                        float      nearestDist = 0f;

                        foreach (Collider c in colliders)
                        {
                            if (c.tag.Equals("Soldier"))
                            {
                                float dist = Vector3.Distance(c.gameObject.transform.position, transform.position);
                                if (nearest == null || dist < nearestDist)
                                {
                                    nearestDist = dist;
                                    nearest     = c.gameObject;
                                }
                            }
                        }

                        if (nearest != null)
                        {
                            FSMManager      g    = nearest.GetComponent <FSMManager>();
                            BasicObjectAttr attr = nearest.GetComponent <BasicObjectAttr>();
                            // We arrive to destination
                            List <SearchConfig> searchConf = g.GetBasicState().GetSearchConfig();
                            foreach (SearchConfig sc in searchConf)
                            {
                                if (sc.doWhenAlert != null)
                                {
                                    IAState st = sc.doWhenAlert.Invoke(obj);
                                    g.setCurrentState(st);
                                }
                            }
                        }
                        lineOfSight.SetStatus(LineOfSight.Status.Alerted);
                    }
                    else
                    {
                        lineOfSight.SetStatus(LineOfSight.Status.Suspicious);
                    }
                }
            }
        }
    }
Esempio n. 5
0
    public override IAState update(GameObject obj)
    {
        // just validation
        if (obj == null || !fromAttr.isAlive().GetValueOrDefault(false))
        {
            return(null);
        }

        foreach (string tag in this.searchTags)
        {
            if (_lineOfSight.SeeByTag(tag))
            {
                List <GameObject> inFView = _lineOfSight.getViewing();
                foreach (GameObject c in inFView)
                {
                    IAState n = notify(c.gameObject, _lineOfSight.GetStatus().Equals(LineOfSight.Status.Alerted));
                    if (n != null)
                    {
                        manager.setCurrentState(n);
                    }
                }
            }
        }

        return(this);
    }
Esempio n. 6
0
    IEnumerator Deteccion()
    {
        while (true)
        {
            if (estadoActual == IAState.Patrol)
            {
                //Un primer if con el area donde te detecta, un segundo if con el angulo , el cono y un tercer if con el raycast para ver si no estas detras de un muro.
                if (Vector3.Distance(transform.position, refJugador.transform.position) < Rangoactivaciondetect)
                {
                    Debug.Log("Detectado");
                    if (Vector3.Angle(this.transform.forward, refJugador.transform.position - this.transform.position) < 30)//Angulo de vision del enemigo cuanto menor mas ciego es
                    {
                        Debug.Log("AnguloDetectado");

                        RaycastHit info;

                        if (Physics.Raycast(this.transform.position, refJugador.transform.position - this.transform.position, out info, distance))
                        {
                            //Debug.Log(info.transform.tag);
                            //Debug.DrawRay(this.transform.position, (refJugador.transform.position - this.transform.position).normalized * distance, Color.red, 0.5f);
                            if (info.transform.tag == "Player")
                            {
                                Debug.Log("Detectadox3");
                                estadoActual = IAState.Move;
                                yield return(new WaitForSeconds(0.01f));
                            }
                        }
                    }
                }
            }

            yield return(new WaitForSeconds(0.01f));
        }
    }
Esempio n. 7
0
    void StateAttacking()
    {
        agent.isStopped = true;
        anim.SetBool("Attacking", true);

        if (Vector3.Distance(transform.position, target.transform.position) < 3)
        {
            if (player)
            {
                //1 golpe por vez

                if (hitting)
                {
                    if (oneHit)
                    {
                        StartCoroutine(WaitHitAnimation());
                        oneHit = false;
                    }
                }

                if (!hitting)
                {
                    StartCoroutine(Attack());
                }
            }
        }

        if (Vector3.Distance(transform.position, target.transform.position) > 5)
        {
            currentState = IAState.Following;
        }
    }
Esempio n. 8
0
    void StateHitted()
    {
        agent.isStopped = true;
        anim.SetBool("Attacking", false);
        anim.SetBool("Hitted", true);

        currentState = IAState.Idle;
    }
        public void TestGetState()
        {
            IAState state    = userMethods.GetState(1);
            var     expected = 1;

            var actual = state.StateNo;

            Assert.True(expected.Equals(actual));
        }
Esempio n. 10
0
    void FixedUpdate()
    {
        if (_isActivated)
        {
             if (_state == IAState.WALKING)
             {
             	_anim.SetBool("isActive", true);
				 transform.GetChild(2).GetChild(0).GetChild(7).GetChild(0).gameObject.SetActive(true);
                 _agent.destination = _target.transform.position;
                 Collider[] entittiesAround = Physics.OverlapSphere(transform.position, _range, _TargetMask);
                 foreach (Collider entity in entittiesAround)
                 {
                     _state = IAState.ATTACKING;
					_anim.SetBool("Attack", true);					
                 }
             }
            if (_state == IAState.ATTACKING)
            {	
				transform.GetChild(2).GetChild(0).GetChild(7).GetChild(0).gameObject.SetActive(true);
                _nextAttack += Time.deltaTime;
				
                if (_nextAttack > _delay) // Delay of attack Animation
                {
                    Collider[] entittiesAround = Physics.OverlapSphere(transform.position, _range, _TargetMask);
                    foreach (Collider entity in entittiesAround)
                    {
                        _target.GetComponent<PlayerAttack>().isAttacked(transform.position);
                    }
                    _nextAttack = 0;
					_anim.SetBool("Attack", false);
                    _state = IAState.WALKING;
                    _agent.Resume();
                }
                else
                    _agent.Stop();
            }
            if (_state == IAState.INACTIVE && _isActivated)
            {
				transform.GetChild(2).GetChild(0).GetChild(7).GetChild(0).gameObject.SetActive(false);           
            	_nextAttack += Time.deltaTime;
            	if (_nextAttack > 10f)
            	{
            		_state = IAState.WALKING;
					_agent.Resume();
					transform.GetChild(2).GetChild(0).GetChild(7).GetChild(0).gameObject.SetActive(true);
					_nextAttack = 0f;
            	}
            }
        }
        else
        {
            _agent.Stop();
			transform.GetChild(2).GetChild(0).GetChild(7).GetChild(0).gameObject.SetActive(false);           
			
        }
    }
Esempio n. 11
0
    void StateFollowing()
    {
        agent.isStopped = false;
        anim.SetBool("Attacking", false);

        agent.SetDestination(target.transform.position);

        if (Vector3.Distance(transform.position, target.transform.position) < 3)
        {
            currentState = IAState.Attacking;
        }
    }
        public void CreateStateTest()
        {
            IFactory      factory  = new Factory();
            List <string> mockData = new List <string>()
            {
                "7", "Test State", "ts", "0.77"
            };
            IAState expected = new AState(mockData, new ConsoleLogger());

            IAState actual = factory.CreateState(mockData, new ConsoleLogger());

            Assert.True(expected.StateCode.Equals(actual.StateCode));
        }
Esempio n. 13
0
 //throw the bottle hold by the AI
 protected void ThrowBottle()
 {
     if (bottle == null)
     {
         AnimationDone();
     }
     else
     {
         actionBase(ActionEnum.Action.ThrowBottle);
         state = IAState.UNINTERACTEABLE;
         animations.ThrowBottle();
     }
 }
Esempio n. 14
0
	// Use this for initialization
	public override void Start () 
	{
		base.Start ();
		this.state = IAState.IDLE;
		this.agent = this.GetComponent<NavMeshAgent> ();
		this.animator = this.GetComponent<Animator> ();
		this.coll = this.GetComponent<CapsuleCollider> ();
		this.agent.stoppingDistance = this.stopingDistance;
		this.agent.speed = this.speed2Walk;
		this.agent.angularSpeed = this.speed2Look;
		this.agent.SetDestination (this.target.position);
		this.StartCoroutine ("CalculatePath");
	}
Esempio n. 15
0
 // Use this for initialization
 public override void Start()
 {
     base.Start();
     this.state    = IAState.IDLE;
     this.agent    = this.GetComponent <NavMeshAgent> ();
     this.animator = this.GetComponent <Animator> ();
     this.coll     = this.GetComponent <CapsuleCollider> ();
     this.agent.stoppingDistance = this.stopingDistance;
     this.agent.speed            = this.speed2Walk;
     this.agent.angularSpeed     = this.speed2Look;
     this.agent.SetDestination(this.target.position);
     this.StartCoroutine("CalculatePath");
 }
Esempio n. 16
0
    IEnumerator Attack()
    {
        //equivalente ao start
        anim.SetTrigger("Hitting");
        oneHit  = true;
        hitting = true;

        yield return(new WaitForSeconds(2f));

        //saida do estado
        hitting      = false;
        currentState = IAState.Idle;
    }
Esempio n. 17
0
	public override void Dead()
	{
		this.coll.enabled = false;
		print (this.name+": MUERTO");
		//
		this.StopAllCoroutines ();
		this.agent.Stop ();
		this.animator.SetTrigger ( "DEAD" );
		this.state = IAState.DEAD;
		//this.GetComponent<MeshRenderer> ().material.color = new Color (0f, 0f, 0f, 1f);
		//this.GetComponent<MeshRenderer> ().material.color = new Color32 (0, 0, 0, 255);
		base.Dead ();
		//Animacion muerte
	}
Esempio n. 18
0
 public override void Dead()
 {
     this.coll.enabled = false;
     print(this.name + ": MUERTO");
     //
     this.StopAllCoroutines();
     this.agent.Stop();
     this.animator.SetTrigger("DEAD");
     this.state = IAState.DEAD;
     //this.GetComponent<MeshRenderer> ().material.color = new Color (0f, 0f, 0f, 1f);
     //this.GetComponent<MeshRenderer> ().material.color = new Color32 (0, 0, 0, 255);
     base.Dead();
     //Animacion muerte
 }
Esempio n. 19
0
    void StateIdle()
    {
        anim.SetBool("Hitted", false);
        agent.isStopped = true;
        anim.SetBool("Attacking", false);

        if (Vector3.Distance(transform.position, target.transform.position) > 3)
        {
            currentState = IAState.Patrol;
        }

        if (Vector3.Distance(transform.position, target.transform.position) < 3)
        {
            currentState = IAState.Attacking;
        }
    }
Esempio n. 20
0
 public void AnimationDone()
 {
     if (actionList.Count > 0)
     {
         actionList.RemoveAt(0);
     }
     anim = false;
     animator.SetBool("Action", false);
     animator.SetBool("walking", false);
     animator.SetBool("throw", false);
     animator.SetBool("pickingUp", false);
     animator.SetBool("drinking", false);
     animator.SetBool("dancing", false);
     animator.SetBool("hide", false);
     animator.SetBool("kick", false);
     animator.SetBool("stun", false);
     animator.SetBool("bottleStrick", false);
     animator.SetBool("slip", false);
     state = IAState.INTERACTEABLE;
 }
Esempio n. 21
0
    public void finishCurrentState()
    {
        // No behavior?
        if (states.Count == 0)
        {
            this.currentState = null;
            return;
        }

        states.Remove(currentState);

        if (states.Count > 0)
        {
            this.currentState = states[states.Count - 1];
        }

        if (this.currentState != null)
        {
            this.currentState.start(gameObject);
        }
    }
Esempio n. 22
0
 void CheckState()
 {
     distancia = this.target.position - this.transform.position;
     if (Close2You())
     {
         if (this.state != IAState.CHASING)
         {
             this.agent.speed = 3f;
             this.state       = IAState.CHASING;
             this.agent.Resume();
         }
     }
     if (Close2Target())
     {
         if (this.state != IAState.ATTACKING)
         {
             this.agent.speed = 0f;
             this.state       = IAState.ATTACKING;
             this.agent.Stop();
         }
     }
 }
Esempio n. 23
0
    void StatePatrol()
    {
        agent.isStopped = false;
        anim.SetBool("Attacking", false);

        agent.SetDestination(patrolPos);

        if (agent.velocity.magnitude < 0.1)
        {
            stoppedTime += Time.deltaTime;
        }
        if (stoppedTime > 3f)
        {
            stoppedTime = 0f;
            patrolPos   = new Vector3(transform.position.x + Random.Range(-10, 10), transform.position.y, transform.position.z + Random.Range(-10, 10));
        }

        if (Vector3.Distance(transform.position, target.transform.position) < 15)
        {
            currentState = IAState.Attacking;
        }
    }
Esempio n. 24
0
    // Use this for initialization
    void Start()
    {
        //Set some initial parameters
        unitID          = UnitManager.instance.GetNewUnitID(behavior.ToString());
        pendingCheckers = new List <Transform>();

        //Set checkers division to the Working IA checkers
        if (!checkersDivisions.Exists(c => c.maxAngle >= 180f))
        {
            checkersDivisions.Add(new BestChecker(180f, 100f));
        }
        checkersDivisions.Sort(delegate(BestChecker bc1, BestChecker bc2)
        {
            return(bc1.maxAngle.CompareTo(bc2.maxAngle));
        });

        //Set state update
        foreach (StateUpdate stateUpdate in stateUpdates)
        {
            availableStates.Add(IAState.CreateNewState(stateUpdate.state, this, stateUpdate.internalStateUpdateTime));
        }

        //If officer, notice to the unit manager
        if (behavior == IABehaviour.OFFICER)
        {
            //If there's no officer zone, set it
            if (UnitManager.instance.GetOfficerZone() == null)
            {
                UnitManager.instance.SetOfficerZone(ZoneManager.instance.GetZone(transform.position));
            }
            UnitManager.instance.SetOfficer(transform);
        }

        //Change state to IDLE
        ChangeState(IAState.IAStateTag.IDLE);
    }
Esempio n. 25
0
 public void ChangeState(IAState.IAStateTag tag)
 {
     IAState.IAStateTag previousState = currentState != null ? currentState.tag : IAState.IAStateTag.IDLE;
     currentState = availableStates.Find(c => c.tag == tag);
     currentState.OnEnable(previousState);
 }
Esempio n. 26
0
    // Update is called once per frame
    void Update()
    {
        //Debug.DrawRay(this.transform.position, (refJugador.transform.position - this.transform.position).normalized * distance, Color.blue, 0.5f);

        switch (estadoActual)
        {
        case IAState.Idle:

            navAgent.SetDestination(transform.position);     //le estoy mandando su propia posicion para que el agente se mantenga quieto

            animator_enem.SetBool("IdleReturn", true);

            if (tiempoEspera == true)          //Espera 2 segundos ya que el tiempo de espera que le he puesto es 2 segundos
            {
                estadoActual = IAState.Patrol; //cuando haya pasado el tiempo cambiamos al estado de patrulla
                Debug.Log("cambioaIdle");
                tiempoEspera = false;
            }

            if (semfcorespera == true)
            {
                StartCoroutine(Tiempoparaespera());
                semfcorespera = false;
            }
            break;

        case IAState.Patrol:

            navAgent.SetDestination(tablaRuta[indiceRuta].position);    //Le mandamos el primer destino de la ruta

            animator_enem.SetBool("IdleReturn", false);

            //MejoraDeteccion

            Debug.Log("EstoyenPatrol");

            if (Vector3.Distance(transform.position, tablaRuta[indiceRuta].position) < 2f)
            {
                indiceRuta++;
                if (indiceRuta >= tablaRuta.Length)    // Cuando lleguemos al ultimo valor de la tabla volveremos al punto inicial
                {
                    indiceRuta = 0;
                }
            }


            break;



        case IAState.Move:

            navAgent.speed = 6;    //Velocidad a la que me persigue el agente
            navAgent.SetDestination(refJugador.transform.position);
            animator_enem.SetFloat("corridocont", 6);


            if (Vector3.Distance(transform.position, refJugador.transform.position) < RangoAtaque)
            {
                if (Vector3.Angle(this.transform.forward, refJugador.transform.position - this.transform.position) < 30)
                {
                    estadoActual = IAState.Attack;
                }
            }
            if (Vector3.Distance(transform.position, refJugador.transform.position) > RangoVision)
            {
                estadoActual = IAState.Return;
            }

            break;

        case IAState.Attack:

            //Que rote todo el rato hacia el
            Quaternion rotTarget = Quaternion.LookRotation(jugador.transform.position - soldado.transform.position);
            soldado.transform.rotation = Quaternion.RotateTowards(soldado.transform.rotation, rotTarget, 2);

            if (CadenciaActive == true)
            {
                if (Vector3.Distance(transform.position, refJugador.transform.position) > RangoAtaqueCuerpoACuerpo)
                {
                    if (Vector3.Distance(transform.position, refJugador.transform.position) < RangoAtaque)
                    {
                        //soldado.transform.LookAt(jugador);

                        CadenciaActive = false;
                        StartCoroutine(DisparoConAnimacion());
                    }
                }
                if (Vector3.Distance(transform.position, refJugador.transform.position) < RangoAtaqueCuerpoACuerpo)
                {
                    StartCoroutine(CuerpoACuerpoAnimacionDmg());


                    CadenciaActive = false;
                }
            }
            if (Vector3.Distance(transform.position, refJugador.transform.position) > RangoVision)
            {
                estadoActual = IAState.Return;
            }


            if (Vector3.Distance(transform.position, refJugador.transform.position) > RangoAtaque)
            {
                navAgent.isStopped = false;
                estadoActual       = IAState.Move;
            }

            break;

        case IAState.Return:
            navAgent.speed = 3;
            semfcorespera  = true;
            animator_enem.SetFloat("corridocont", 3);
            animator_enem.SetBool("IdleReturn", true);

            estadoActual = IAState.Idle;


            break;
        }
        Debug.Log(estadoActual);
        Debug.Log("estadodeahora");
    }
Esempio n. 27
0
 //slip on the floor
 protected void Slip()
 {
     actionBase(ActionEnum.Action.Slip);
     state = IAState.UNINTERACTEABLE;
     animations.Slip();
 }
Esempio n. 28
0
	void CheckState () 
	{
		distancia = this.target.position - this.transform.position;
		if (Close2You ()) 
		{
			if (this.state != IAState.CHASING) 
			{
				this.agent.speed = 3f;
				this.state = IAState.CHASING;
				this.agent.Resume();
			}
		}
		if (Close2Target ()) 
		{	
			if (this.state != IAState.ATTACKING) 
			{
				this.agent.speed = 0f;
				this.state = IAState.ATTACKING;
				this.agent.Stop();
			}
		}
	}
Esempio n. 29
0
 public IAState setPrevious(IAState previous)
 {
     this.previousState = previous;
     return(this);
 }
Esempio n. 30
0
    public void Activate(bool state)
    {
    	
        _isActivated = state;
        if (state)
        {
			_agent.Resume();
            _state = IAState.WALKING;
        }
        else
            _state = IAState.INACTIVE;
    }
Esempio n. 31
0
 /// <summary>
 /// Altera o estado da maquina de estados
 /// </summary>
 /// <param name="newState">Novo estado que será definido</param>
 private void ChangeState(IAState newState)
 {
     currentState = newState;
 }
Esempio n. 32
0
    public void TakeDamage(Vector3 enemypos)
    {
		float tmpX, tmpZ;
		
		tmpX = transform.position.x - enemypos.x;
		tmpZ = transform.position.z - enemypos.z;
		GetComponent<Rigidbody>().AddForce(new Vector3(tmpX * violence, 0, tmpZ * violence));
		System.Random rnd = new System.Random();
		int angle = rnd.Next(180, 360);
		transform.Rotate(new Vector3(0, angle, 0) * 30 * Time.deltaTime);
		_state = IAState.INACTIVE;
		_anim.SetBool("isActive", false);
    }
Esempio n. 33
0
    // Use this for initialization
	void Start () {
        _agent = GetComponent<NavMeshAgent>();
        src = GetComponent<AudioSource>();
        _state = IAState.INACTIVE;
        _anim = GetComponent<Animator>();
	}
Esempio n. 34
0
 private void ChangeIAState(IAState iaState)
 {
     m_IAState = iaState;
 }