Esempio n. 1
0
 private void OnCollisionEnter(Collision collision)
 {
     if (collision.gameObject.tag == "Player")
     {
         currentState = AIstate.Fleeing;
     }
 }
    public void Attack()
    {
        //No need to check the closest target, since we should lock our attention to one troop at least as long as it's in the reachRadius

        if (Vector2.Distance(transform.position, currentTarget.position) < reachRad && currentTarget != gameObject.transform)
        {
            //Attack the target
            attackTimer -= Time.deltaTime;
            if (attackTimer <= 0)
            {
                List <Transform> enemyUnits = targetManager.FindAllTargetsWithinRadius(gameObject.transform, thisPlayer, attackRad + 0.1f);

                foreach (Transform unit in enemyUnits)
                {
                    IDamageable healthScript = unit.GetComponent <IDamageable>();
                    if (healthScript != null)
                    {
                        healthScript.ApplyDamage(attackPower);
                    }
                }
                attackTimer += attackPerSecond;
                AudioFW.Play("Unit_DarkK_Attack");
            }
        }
        else if (Vector2.Distance(transform.position, currentTarget.position) < aggroRadius)
        {
            currentState = AIstate.Aggro;
        }
        else
        {
            currentState = AIstate.Navigate;
            //DeListen target death notification
        }
    }
Esempio n. 3
0
    void AIAgent()
    {
        if (initiateAI)
        {
            aiState = AIstate.resetAI;

            float multipier = 0;

            if (!gotRandom)
            {
                storeRandom = RetureRandom();
                gotRandom = true;
            }

            if (!closeCombat)
            {
                multipier += 30;
            }
            else
            {
                multipier -= 30;

            }

            if (storeRandom + multipier < 50)
            {
                Attack();
            } else
                Movement();
        }
    }
Esempio n. 4
0
    public void Attack()
    {
        //No need to check the closest target, since we should lock our attention to one troop at least as long as it's in the reachRadius

        if (Vector2.Distance(transform.position, currentTarget.position) < reachRad && currentTarget != gameObject.transform)
        {
            //Attack the target
            attackTimer -= Time.deltaTime;
            if (attackTimer <= 0)
            {
                currentTarget.GetComponent <IDamageable>().ApplyDamage(attackPower);
                attackTimer += attackPerSecond;
                AudioFW.Play("Unit_Knight_Attack");
            }
        }
        else if (Vector2.Distance(transform.position, currentTarget.position) < aggroRadius)
        {
            currentState = AIstate.Aggro;
        }
        else
        {
            currentState = AIstate.Navigate;
            //DeListen target death notification
        }
    }
Esempio n. 5
0
 private void OnCollisionEnter2D(Collision2D other)
 {
     if (other.gameObject.CompareTag("player") && !haveBox)
     {
         state = AIstate.SEARCH_BOX_PATH;
     }
 }
Esempio n. 6
0
        void HandleFarInSight()
        {
            //距離が一定以下なら「視界に入っており、近くにいる」状態になる
            if (distance <= distancelimit && insight && !states.isrunning)
            {
                aiState = AIstate.closeinsight;
            }

            insight = CheckInsight();

            if (time > 0 && insight)
            {
                states.WalkToTarget(target, walkspeed);
            }


            if (time < 0 && insight)
            {
                states.RunToTargetAndAttack(lastpos, runspeed);
            }



            //インターバル時間がゼロ以上で視界に入っていた場合近寄る
            //そうでない場合突進する(歩く速度よりも速く、制限距離まで近づく。)
        }
Esempio n. 7
0
 void FindCovers()
 {
     Collider[] hitColliders = Physics.OverlapSphere(transform.position, 30);
     if (hitColliders.Length > 0)
     {
         for (int i = 0; i < hitColliders.Length; i++)
         {
             if (hitColliders[i].gameObject.GetComponent <CoverObject>())
             {
                 if (!hitColliders[i].gameObject.GetComponent <CoverObject>().owner)
                 {
                     Vector3 direction = EnemyToAttack.transform.position - hitColliders[i].transform.position;//seems wrong
                     Vector3 forward   = hitColliders[i].transform.forward;
                     float   angle     = Vector3.Angle(direction, forward);
                     if (angle < 180f)
                     {
                         if (!AvailableCover.Contains(hitColliders[i].transform))
                         {
                             AvailableCover.Add(hitColliders[i].transform);
                         }
                     }
                 }
             }
         }
         if (AvailableCover.Count <= 0)
         {
             aiState = AIstate.Attack;
         }
     }
 }
Esempio n. 8
0
        void HandleCloseinsight()
        {
            insight = CheckInsight();
            //距離が一定以上で視界に入っていたら、「farinsight」
            if (distance > distancelimit && insight && time > -5f)
            {
                aiState = AIstate.farinsight;
            }
            if (distance < distancelimit && !insight)//距離が一定以下で視界に入ってない場合
            {
                aiState = AIstate.behindclose;
            }
            if (time < 0)//行動制限が解除されたら
            {
                if (states.canMove && insight)
                {
                    int c_attacknum = Random.Range(0, em.c_attacks.Count); //呼び出す近接攻撃を決定する
                    animattacknum = c_attacknum;                           //animattacknumはc_attacknumを代入した数になる
                    states.CloseAttackaction(c_attacknum);                 //c_attacksに格納されたアニメーションの中からランダムに選び近接攻撃を仕掛ける


                    states.canMove = false;
                }
            }
        }//クールダウン時間がゼロで、視界に入っていたら近接攻撃する
Esempio n. 9
0
        }//クールダウン時間がゼロで、視界に入っていたら近接攻撃する

        //バグ:この状態で遠くに離れると、敵が動かなくなりそこでインターバルが0になるたびにbehindattackをし続けるので、振り向かせる必要がある
        void HandleCloseNotinsight()
        {
            insight = CheckInsight();

            if (distance < distancelimit && insight && states.canMove)
            {//距離が一定以下で視界に入っており、canmoveがtrueの場合、closeinsightになる
                aiState = AIstate.closeinsight;
            }
            //距離が離れていたら、「遠くにいる」
            if (distance > distancelimit)
            {
                aiState = AIstate.farinsight;
            }
            //視界に入っておらず、行動制限時間が0以下の場合
            if (!insight && time <= 0)
            {
                if (states.canMove)
                {
                    int b_attacknum = Random.Range(0, em.b_attacks.Count); //背後への攻撃のアニメーションを決定する
                    animattacknum = b_attacknum;
                    states.CloseBehindaction(b_attacknum);                 //背後への攻撃アニメーションを行う

                    states.canMove = false;
                }
            }
        }
Esempio n. 10
0
    IEnumerator StunCooldown(float time)
    {
        currentState = AIstate.Stun;
        yield return(new WaitForSeconds(time));

        currentState = AIstate.Navigate;
    }
Esempio n. 11
0
        void Update()
        {
            delta = Time.deltaTime;
            dis   = distanceFromTarget();
            angle = angleToTarget();
            if (target)
            {
                dirToTarget = target.position - transform.position;
            }

            RaycastToTarget();
            switch (aiState)
            {
            case AIstate.far:
                HandleFarSight();
                break;

            case AIstate.close:
                HandleCloseSight();
                break;

            case AIstate.inSight:
                InSight();
                break;

            case AIstate.attacking:
                if (estates.canMove)
                {
                    aiState = AIstate.inSight;
                    //estates.agent.enabled = true;
                }
                break;
            }
            estates.Tick(delta);
        }
Esempio n. 12
0
        void HandleFarSight()
        {
            if (target == null)
            {
                return;
            }

            _frame++;
            if (_frame > frameCount)
            {
                _frame = 0;

                if (dis < sight)
                {
                    if (angle < fov_angle)
                    {
                        aiState = AIstate.close;
                    }
                }
                else
                {
                    if (!states.navAgent.pathPending && states.navAgent.remainingDistance < 0.5f)
                    {
                        GotoNextPoint();
                    }
                }
            }
        }
Esempio n. 13
0
 private void InvestigateUpdate()
 {
     target_position = investigatePosition;
     if (CheckPlayerInRange(calcDetectionRange()))
     {
         state = AIstate.hunting;
     }
 }
Esempio n. 14
0
 void OnPathComplete(Path p)
 {
     if (!p.error)
     {
         path            = p;
         currentWaypoint = 0;
         state           = AIstate.TravelPath;
     }
 }
Esempio n. 15
0
    private void CheckAi()
    {
        int nbrBoxes = spawner.ReturnNbrBoxes();

        if (nbrBoxes <= 0)
        {
            state = AIstate.IDLE;
        }
    }
Esempio n. 16
0
 public void EndOnRails()
 {
     speed = normalSpeed;
     state = AIstate.patrol;
     if (doRailsTeleport)
     {
         Monster.GetComponent <Transform>().position = RailsOnCompleteteleportPos;
     }
     currentWaypoint = int.MaxValue;
 }
Esempio n. 17
0
    //public void SetState(AIstate s)
    //{
    //    state = s;
    //}

    public void InvestigatePosition(Vector2 pos)
    {
        if (state != AIstate.sleeping)
        {
            state = AIstate.investigate;
            investigatePosition.x = pos.x;
            investigatePosition.y = pos.y;
            return;
        }
    }
Esempio n. 18
0
    IEnumerator BreakBlock()
    {
        _breakingBlock = true;
        yield return(new WaitForSeconds(.1f));

        Debug.Log("player " + playerID + " is breaking a block!");


        //face block
        if (target != null)
        {
            float xDiff = transform.position.x - target.position.x;
            float yDiff = transform.position.y - target.position.y;

            if (xDiff < -.5f)
            {
                _direction = PlayerDir.right;
            }
            if (xDiff > .5f)
            {
                _direction = PlayerDir.left;
            }
            if (yDiff < -.5f)
            {
                _direction = PlayerDir.up;
            }
            if (yDiff > .5f)
            {
                _direction = PlayerDir.down;
            }

            int health = 0;
            if (target.gameObject.GetComponent <BreakableRock>() != null)
            {
                health = target.gameObject.GetComponent <BreakableRock>().health;
            }

            while (health > 0)
            {
                AxeDown();

                yield return(new WaitForSeconds(.5f));

                AxeUp();

                yield return(new WaitForSeconds(.5f));

                health--;
            }
        }
        DetermineNewTarget();
        state          = AIstate.TravelPath;
        _breakingBlock = false;
        _stuckNumber   = 0;
    }
Esempio n. 19
0
    private void Awake()
    {
        //Initialize the correct UnitType, and place it in variable thisUnit
        unitContainer = FindObjectOfType <UnitTypeContainer>();
        unitTypes     = unitContainer.unitTypes;
        for (int i = 0; i < unitTypes.Count; i++)
        {
            if (unitTypes[i].unitTypeName.Equals(unitTypeName))
            {
                thisUnit = unitTypes[i]; break;
            }
        }                                                                                                                                     //Basic For-loop to find the correct UnitType from container

        //Initialize the UnitType stats to this instance
        health          = thisUnit.health;
        attackPower     = thisUnit.attackPower;
        attackPerSecond = thisUnit.attackPerSecond;
        baseSpeed       = thisUnit.baseSpeed;
        sizeRadius      = thisUnit.sizeRadius;
        attackRadius    = thisUnit.attackRadius;
        aggroRadius     = thisUnit.aggroRadius;
        targets         = thisUnit.targets;
        characteristcs  = thisUnit.characteristcs;

        //Initialize some private stats as well:
        attackRad   = attackRadius;     //The tolrance distance for when the enemy starts "Attacking" the target instead of "Navigating" towards it.
        reachRad    = attackRad * 1.2f; //Once the "Attacking" has started, we need to enlargen the attackDiameter, so that there won't occur any "following jitter", where the unit stops, but has to start navigating agian, because the enemy is out-of-reach on the next update.
        attackTimer = attackPerSecond;

        //Initialize the NavMeshAgent and assign stats to the agent's parameters
        agent        = GetComponent <NavMeshAgent>();
        agent.speed  = baseSpeed;
        agent.radius = sizeRadius;

        //Assert the correct player id:
        thisPlayer  = GetComponentInParent <PlayerID>().playerID;
        enemyPlayer = (thisPlayer == 1) ? 2 : 1;

        //Assert the correct TargetInformation to this unit
        targetInfo = GetComponent <UnitTargetInfo>();
        targetInfo.SetTargetEnum(targets);
        targetInfo.SetCharacteristicsEnum(characteristcs);

        //Add the unit's Transform to the current battlefield units Hashset:
        targetManager = FindObjectOfType <TargetingManager>();
        targetManager.RegisterUnit(gameObject.transform, thisPlayer);

        //Initialize the Unit States, so the game will orient the unit correctly starting from Update()
        currentState  = AIstate.NoState;
        previousState = AIstate.NoState;

        AudioFW.Play("Unit_Knight_Ready");
    }
Esempio n. 20
0
 public void OnTargetDeath()
 {
     UnListenTarget();
     if (currentState == AIstate.Navigate)
     {
         StartCoroutine(StunCooldown(0.2f)); //Otherwise the Navigating unit will continue navigating towards currentTarget. Now Stun resets the target.
     }
     else
     {
         currentState = AIstate.Navigate;
     }
 }
Esempio n. 21
0
 private void HuntUpdate()
 {
     target_position = playerTransform.position;
     if (!CheckPlayerInRange(calcDetectionRange(loseDetectionMosifier)))
     {
         Monster.GetComponent <SoundPlayer>().Stop(2);
         state = AIstate.patrol;
     }
     if (InSafezone())
     {
         Monster.GetComponent <SoundPlayer>().Stop(2);
         state = AIstate.patrol;
     }
 }
Esempio n. 22
0
    private void FixedUpdate()
    {
        if (path == null)
        {
            return;
        }

        if (!atEndOfPath())
        {
            Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - monsterRB.position).normalized;
            Vector2 force     = direction * speed * Time.deltaTime;
            monsterRB.AddForce(force);

            float distance = Vector2.Distance(monsterRB.position, path.vectorPath[currentWaypoint]);
            if (distance < nextWaypointDistance)
            {
                currentWaypoint++;
            }
        }

        monsterPosition = Monster.GetComponent <Transform>().position;

        switch (state)
        {
        case AIstate.patrol:
            PatrolUpdate();
            break;

        case AIstate.hunting:
            HuntUpdate();
            break;

        case AIstate.investigate:
            InvestigateUpdate();
            break;

        case AIstate.on_rails:
            OnRailsUpdate();
            break;

        case AIstate.sleeping:
            SleepingUpdate();
            break;

        default:
            state = AIstate.patrol;
            break;
        }
    }
Esempio n. 23
0
        void HandleCloseSight()
        {
            _close++;
            if (_close > closeCount)
            {
                _close = 0;

                if (dis > sight || angle > fov_angle)
                {
                    aiState = AIstate.far;
                    return;
                }
            }
            RaycastToTarget();
        }
Esempio n. 24
0
    IEnumerator Think()
    {
        while (true)
        {
            switch (state)
            {
            case AIstate.idle:
                float dist = Vector3.Distance(target.position, transform.position);
                if (dist < chasingDistance)
                {
                    state = AIstate.chasing;
                    animator.SetBool("chasing", true);
                }
                nm.SetDestination(transform.position);
                break;

            case AIstate.chasing:
                dist = Vector3.Distance(target.position, transform.position);
                if (dist > chasingDistance)
                {
                    state = AIstate.idle;
                    animator.SetBool("chasing", false);
                }
                if (dist < attackingDistance)
                {
                    state = AIstate.attacking;
                    animator.SetBool("attacking", true);
                }
                nm.SetDestination(target.position);
                break;

            case AIstate.attacking:
                dist = Vector3.Distance(target.position, transform.position);
                nm.SetDestination(transform.position);
                if (dist > attackingDistance)
                {
                    state = AIstate.chasing;
                    animator.SetBool("attacking", false);
                }
                break;

            default:
                break;
            }

            yield return(new WaitForSeconds(0.2f));
        }
    }
Esempio n. 25
0
    IEnumerator Think()
    {
        while (true)
        {
            switch (aiState)
            {
            case AIstate.idle:
                float distance = Vector3.Distance(target.position, transform.position);
                if (distance < distanceThreshold)
                {
                    aiState = AIstate.chasing;
                }
                Zombie.SetDestination(transform.position);
                break;

            case AIstate.patrol:
                distance = Vector3.Distance(target.position, transform.position);
                if (distance < distanceThreshold)
                {
                    aiState = AIstate.chasing;
                }
                //random directions


                break;

            case AIstate.chasing:
                Zombie.SetDestination(target.position);
                distance = Vector3.Distance(target.position, transform.position);
                if (distance > distanceThreshold)
                {
                    aiState = AIstate.idle;
                }
                break;

            case AIstate.attack:
                Zombie.SetDestination(target.position);


                break;

            default:
                break;
            }
        }
    }
Esempio n. 26
0
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("box"))
        {
            Destroy(other.gameObject);
            takenBoxPos = other.transform.position;
            spawner.DeleteBoxPos(takenBoxPos);
            haveBox = true;
            pathFinder.DeletePath(goalNode, startNode);
            state = AIstate.SEARCH_TRUCK_PATH;
        }

        if (other.CompareTag("AITruck") && haveBox)
        {
            haveBox = false;
            pathFinder.DeletePath(goalNode, startNode);
            state = AIstate.SEARCH_BOX_PATH;
        }
    }
Esempio n. 27
0
    public void Navigate()
    {
        closestTarget = targetManager.FindClosestTarget(transform, thisPlayer, false);
        if (closestTarget == null)
        {
            closestTarget = gameObject.transform;
        }

        if (Vector3.Distance(transform.position, closestTarget.position) < attackRad)
        {
            currentState = AIstate.Attack;
            ChangeTarget(closestTarget);
        }
        else if (Vector3.Distance(transform.position, closestTarget.position) < aggroRadius)
        {
            currentState = AIstate.Aggro;
            ChangeTarget(closestTarget);
        }
    }
    public void Attack()
    {
        //No need to check the closest target, since we should lock our attention to one troop at least as long as it's in the reachRadius

        if (Vector2.Distance(transform.position, currentTarget.position) < reachRad && currentTarget != gameObject.transform)
        {
            //Attack the target
            attackTimer -= Time.deltaTime;
            if (attackTimer <= 0)
            {
                uninterruptedAttacks++;
                AudioFW.Play("Unit_Infernodragon_Attack");
                if (uninterruptedAttacks < 5)
                {
                    //8.5% damage
                    currentTarget.GetComponent <IDamageable>().ApplyDamage(Mathf.FloorToInt(attackPower * 0.085f));
                }
                else if (uninterruptedAttacks < 10)
                {
                    //28.5% damage
                    currentTarget.GetComponent <IDamageable>().ApplyDamage(Mathf.FloorToInt(attackPower * 0.285f));
                }
                else
                {
                    //100% attackPower
                    currentTarget.GetComponent <IDamageable>().ApplyDamage(Mathf.FloorToInt(attackPower * 1f));
                }

                attackTimer += attackPerSecond;
            }
        }
        else if (Vector2.Distance(transform.position, currentTarget.position) < aggroRadius)
        {
            currentState         = AIstate.Aggro;
            uninterruptedAttacks = 0;
        }
        else
        {
            currentState         = AIstate.Navigate;
            uninterruptedAttacks = 0;
            //DeListen target death notification
        }
    }
Esempio n. 29
0
    public void InitOnRails(GameObject RailsStartPoint, GameObject RailsEndPoint, GameObject RailsTeleportPoint = null)
    {
        if (RailsStartPoint && RailsEndPoint)
        {
            speed = railsSpeed;
            state = AIstate.on_rails;
            Monster.GetComponent <Transform>().position = RailsStartPoint.GetComponent <Transform>().position;
            target_position = RailsEndPoint.GetComponent <Transform>().position;

            if (RailsTeleportPoint)
            {
                RailsOnCompleteteleportPos = RailsTeleportPoint.GetComponent <Transform>().position;
                doRailsTeleport            = true;
            }
            else
            {
                doRailsTeleport = false;
            }
        }
    }
Esempio n. 30
0
        void HandleFarSight()
        {
            if (target == null)
            {
                return;
            }
            _frame++;
            if (_frame > frameCount)
            {
                _frame = 0;

                if (dis < sight)
                {
                    if (angle < fov_angle)
                    {
                        aiState = AIstate.close;
                    }
                }
            }
        }
Esempio n. 31
0
        void RaycastToTarget()
        {
            RaycastHit hit;
            Vector3    origin = transform.position;

            origin.y += 0.5f;
            Vector3 dir = dirToTarget;

            dir.y += 0.5f;
            if (Physics.Raycast(origin, dir, out hit, sight, states.ignoreLayers))
            {
                StateManager st = hit.transform.GetComponentInParent <StateManager>();
                if (st != null)
                {
                    states.rotateToTarget = true;
                    aiState = AIstate.inSight;
                    states.SetDestination(target.position);
                }
            }
        }
Esempio n. 32
0
    protected override void UpdateAI()
    {

        if ((!isAlive) && hp > -100)
        {
            audioHandler.PlaySound("ImpactMetal_big");
            hp = -200;
        } 

        if (transform.position.y < 10F)
        {
            shootingCooldown -= Time.deltaTime;
            moveCooldown -= Time.deltaTime;
        }

        if (state == AIstate.SUMMONED)
        {
            state = AIstate.SWAP_POS;
            if (pattern == AIpattern.RANDOM)
            {
                targetPosition = new Vector2(Random.Range(-9F, 9F), Random.Range(5F, 8F));
            }

            if (pattern == AIpattern.WAVE)
            {
                patternX = 10F * -patternDir;
                targetPosition = new Vector2(patternX, Mathf.Sin(patternX) * 2F + 6F);
            }
        }

        if (state == AIstate.SWAP_POS)
        {
            if (shootingCooldown < 0) Shoot(player);

            if (((Vector2)transform.position - targetPosition).magnitude <= 1.5F)
            {

                if (pattern == AIpattern.RANDOM)
                {
                    moveCooldown = Random.Range(5F, 8F);
                    state = AIstate.SHOOTING;
                }

                if (pattern == AIpattern.WAVE)
                {
                    patternX = patternX + 0.5F * patternDir;
                    targetPosition = new Vector2(patternX, Mathf.Sin(patternX) * 2F + 6F);
                }
            }
        }

        if (state == AIstate.SHOOTING)
        {
            if (shootingCooldown < 0) Shoot(player);
            if (moveCooldown < 0)
            {
                if (pattern == AIpattern.RANDOM)
                {
                    state = AIstate.SWAP_POS;
                    targetPosition = new Vector2(Random.Range(-9F, 9F), Random.Range(5F, 8F));
                }
            }
        }
    }
Esempio n. 33
0
    protected override void UpdateAI()
    {
        if (transform.position.y < 10F)
        {
            shootingCooldown -= Time.deltaTime;
            stateTimer -= Time.deltaTime;
        }

        if (state == AIstate.STOPPED)
        {
            if (stateTimer < 0)
            {
                rotation = (rotation + 1) % 3;

                if (Random.Range(0, 3) > 0)
                {
                    int sndNum = Random.Range(2, 5);
                    audioHandler.PlaySound("Demon laughter" + sndNum);
                }

                if (rotation == 0)
                {
                    state = AIstate.ATTACKING_2;
                    stateTimer = 0.5F;
                    substate = 0;
                    //anim.SetTrigger(anim_A1);
                }

                if (rotation == 1)
                {
                    state = AIstate.ATTACKING_1;
                    stateTimer = 4F;
                    //anim.SetTrigger(anim_A2);
                }

                if (rotation == 2)
                {
                    state = AIstate.WALKING;
                    stateTimer = 2.8F;
                    //anim.SetTrigger(anim_Dash);
                }

            }
        }

        if (state == AIstate.WALKING)
        {
            if (stateTimer < 0)
            {
                transform.position = new Vector3(-patternDir * -7, transform.position.y, 0);
                patternDir = patternDir * -1;
                state = AIstate.STOPPED;
                stateTimer = 1.5F;
            } else
            {
                transform.position = new Vector3(-patternDir * (stateTimer * 5F - 7), transform.position.y, 0);
            }
        }

        if (state == AIstate.ATTACKING_1)
        {
            if (stateTimer < 0)
            {
                state = AIstate.STOPPED;
                stateTimer = 1.5F;
                //anim.SetTrigger(anim_A2_end);
            }

            if (shootingCooldown < 0) Shoot();
        }

        if (state == AIstate.ATTACKING_2)
        {
            if (substate == 0 && stateTimer < 0)
            {
                Shoot2();
                stateTimer = 0.2F;
                substate++;
            }
            else if (substate == 1 && stateTimer < 0)
            {
                stateTimer = 0.5F;
                GetComponent<Rigidbody2D>().AddForce(new Vector3(0, 5000F, 0));
                substate++;
            }
            else if (substate == 2 && stateTimer < 0)
            {
                Shoot2();
                stateTimer = 0.7F;
                substate++;
            }
            else if (substate == 3 && stateTimer < 0)
            {
                Shoot2();
                stateTimer = 0.1F;
                substate++;
            }
            else if (substate == 4 && stateTimer < 0)
            {
                state = AIstate.STOPPED;
                stateTimer = 1.5F;
            }
        }
    }
Esempio n. 34
0
        public override void Update(GameTime gameTime)
        {
            _victim = (Game as Game1)._player;
            Vector2 toPlayer = this._position - _victim.GetPosition();

            #region Check state

            if (toPlayer.LengthSquared() < Constants.GruselUte_SightRange * Constants.GruselUte_SightRange)
            {
                _state = AIstate.AGGRO;
            }
            else
            {
                _state = AIstate.IDLE;
            }

            switch (_state)
            {
                case AIstate.IDLE:
                    IdleBehavior(gameTime);
                    break;
                case AIstate.AGGRO:
                    AggroBehavior(gameTime);
                    break;
                default:
                    IdleBehavior(gameTime);
                    break;
            }
            #endregion

            _cm.Update(gameTime);

            base.Update(gameTime);
        }
Esempio n. 35
0
    void DecideState()
    {
        Enemies.RemoveAll(item => item == null);
        if (Enemies.Count > 0)
        {
            bool enemy2attackinlist = false;
            if (!EnemyToAttack)
            {
                foreach (GameObject enGo in Enemies)
                {
                    if (EnemyToAttack == enGo)
                    { enemy2attackinlist = true; }
                    if (enGo != null)
                    {
                        Vector3 direction = enGo.transform.position - transform.position;
                        float angle = Vector3.Angle(direction, transform.forward);
                        if (angle < 180f)
                        {
                            RaycastHit hit;
                            if (Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, 15))
                            {
                                if (hit.collider.gameObject.GetComponent<CharacterStats>())
                                {
                                    if (hit.collider.gameObject.GetComponent<CharacterStats>().Id != GetComponent<CharacterStats>().Id)
                                    {
                                        //Debug.Log("!!!");
                                        EnemyToAttack = hit.collider.gameObject;
                                    }
                                }
                                if (hit.collider.gameObject.GetComponentInParent<CharacterStats>())
                                {
                                    if (hit.collider.gameObject.GetComponentInParent<CharacterStats>().Id != GetComponent<CharacterStats>().Id)
                                    {
                                        //Debug.Log("!!!");
                                        EnemyToAttack = hit.collider.gameObject.GetComponentInParent<CharacterStats>().gameObject;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {

                    }
                }
                if(enemy2attackinlist==false)
                {
                    EnemyToAttack = null;
                }
            }
            else {
                if (!Decision)
                {   //Compare weapons
                    if (SharedFunctions.CompareWeapon(weaponManager.ActiveWeapon, EnemyToAttack.GetComponent<WeaponManager>().ActiveWeapon))
                    {   //Our weapon is superior, so attack
                       // Debug.Log("superior");
                        aiState = AIstate.Attack;
                    }
                    else {  //Our weapon is inferior, so take cover
                      //  Debug.Log("inferior");
                        aiState = AIstate.GoToCover;
                    }

                    Decision = true;
                }
            }

        }
        else
        {
            aiState = AIstate.Patrol;
            anim.SetBool("Aim", false);
        }

        //Are we in Cover?
        if (aiState == AIstate.GoToCover)
        {
            if (closestCover != null)
            {
                float distance = Vector3.Distance(transform.position, closestCover.transform.position);
                if (distance < 1.5f)
                {
                    //character might get stuck,try to increase 1.3

                    aiState = AIstate.InCover;

                }
                /*
                CoverObject cObj = closestCover.GetComponent<CoverObject> ();

                if (cObj.owner)
                {
                    if (cObj != this.gameObject)
                    {
                        //AvailableCover.Clear ();
                        //closestCover = null;
                    }
                    else
                    {	Debug.Log ("red");

                    }
                }
                else
                {
                    cObj.owner = this.gameObject;
                }*/

            }
        }
    }
Esempio n. 36
0
    void FindCovers()
    {
        Collider[] hitColliders = Physics.OverlapSphere(transform.position, 30);
        if (hitColliders.Length > 0)
        {
            for (int i = 0; i < hitColliders.Length; i++)
            {
                if (hitColliders[i].gameObject.GetComponent<CoverObject>())
                {
                    if (!hitColliders[i].gameObject.GetComponent<CoverObject>().owner)
                    {
                        Vector3 direction = EnemyToAttack.transform.position - hitColliders[i].transform.position;//seems wrong
                        Vector3 forward = hitColliders[i].transform.forward;
                        float angle = Vector3.Angle(direction, forward);
                        if (angle < 180f)
                        {
                            if (!AvailableCover.Contains(hitColliders[i].transform))
                            {
                                AvailableCover.Add(hitColliders[i].transform);
                            }
                        }

                    }
                }

            }
            if (AvailableCover.Count <= 0)
                aiState = AIstate.Attack;

        }
    }
Esempio n. 37
0
	//Checks if the player is nearby
	void DecideState(){
		if (Enemies.Count > 0) {
			if(!EnemyToAttack){
				foreach(GameObject enGo in Enemies){
					if(enGo.tag=="Player")
						EnemyToAttack=enGo;
				}
			}
			else{
				aiState = AIstate.Attack;
			}
		}
	}
Esempio n. 38
0
    void CheckDistance()
    {
        float distance = Vector3.Distance(transform.position, pc.enemy.position);

        if(distance > changeStateTolerance)
        {
            if(aiState != AIstate.resetAI)
            {
                aiState = AIstate.closeState;
            }

            closeCombat = true;
        }
        else
        {
            if(aiState != AIstate.resetAI)
            {
                aiState = AIstate.normalState;
            }

             if (closeCombat)
             {
                if (!gotRandom)
                {
                    storeRandom = RetureRandom();
                    gotRandom = true;
                }

                if(storeRandom < 60)
                {
                    Movement();
                }
             }

            closeCombat = false;
        }
    }
Esempio n. 39
0
    void ResetAI()
    {
        aiTimer += Time.deltaTime;

        if(aiTimer > aiStateLife)
        {
            initiateAI = false;
            pc.horizontal = 0;
            pc.vertical = 0;
            aiTimer = 0;

            gotRandom = ralse;
            storeRandom = RetureRandom();

            if (storeRandom < 50)
                aiState = AIstate.normalState;
            else
                aiState = AIstate.closeState;

            curNumAttacks = 1;
            randomizeAttacks = false;
        }
    }
Esempio n. 40
0
	void DecideState(){
		
		#region tenemos un enmegio ?
		if (Enemies.Count > 0) {
			if (!enemyToAtack) {
				//Debug.Log ("no hay enmigo ha Atacar");
				foreach (GameObject enGo in Enemies) {
					Vector3 direction = enGo.transform.position - transform.position;//direcion del personaje enemigo
					float angle = Vector3.Angle (direction, transform.forward);//encontrar el angula hacia el enemigo
					//Debug.Log("anguiloooooooooooooo"+ angle);
					if (angle < 110f * 0.5f ) {//angulo al que debe estar el enmigo
							Debug.Log("en Angulo de vision");

						RaycastHit hit;
						if (Physics.Raycast (transform.position + transform.up, direction.normalized, out hit, 20)) {//20 es el radio de la mira
							Debug.Log("dentro de la vision ");

							if (hit.collider.GetComponent<statsDePersonajes> ()) {//no funciona esta linea
								Debug.Log(" enemigo");
								if (hit.collider.GetComponent<statsDePersonajes> ().Id != GetComponent<statsDePersonajes> ().Id) {
									Debug.Log ("!!!!!!!!!!!!!!!");
									enemyToAtack = hit.collider.gameObject;
								}
							}

							/*if (hit.collider.GetComponentInParent<statsDePersonajes> ()) {//no funciona esta linea
								Debug.Log("tealvez enemigo juagador");
								Debug.Log("id de jugador  "+ hit.collider.GetComponentInParent<statsDePersonajes> ().Id );
								if (hit.collider.GetComponentInParent<statsDePersonajes> ().Id != GetComponent<statsDePersonajes> ().Id) {//no entra
									Debug.Log ("!!!!!!!!!!!!!!!");
									enemyToAtack = hit.collider.gameObject;
								}
							}*/
						
						}
					}
				}
			}//if (!enemyToAtack)
			else{//si ya hay un enemigo
				//no hemos decidido todavia
				if(!decision){
					Debug.Log("Hacer decicion");
					//compare las aramas
					//if(compararArma(weponManger.activeWeapon,enemyToAtack.GetComponentInChildren<managerDeArmasjugador>().armaActiva )){
					if(enemyToAtack.GetComponent<managerDeArmasEnemigo>()){
					if(compararArma(weponManger.activeWeapon,enemyToAtack.GetComponent<managerDeArmasEnemigo>().activeWeapon)){
						//el arma del enemico es superior
						//aiState=AIstate.Atack;
						aiState=AIstate.GoToCover;
					}else{
						//el arma enemiga es inferior tomames covertuira
						aiState=AIstate.GoToCover;		
					}
				
				
				decision=true;//solo una vez se toma esta decision
				}

					if(enemyToAtack.GetComponentInChildren<managerDeArmasjugador>()){
						
						if(compararArma(weponManger.activeWeapon,enemyToAtack.GetComponentInChildren<managerDeArmasjugador>().armaActiva)){
							//el arma del enemico es superior
							//aiState=AIstate.Atack;
							Debug.Log("Ve a cobertura");
							aiState=AIstate.GoToCover;
						}else{
							//el arma enemiga es inferior tomames covertuira
							aiState=AIstate.GoToCover;		
						}


						decision=true;//solo una vez se toma esta decision
					}
				
				}
				
			}
		}
		#endregion

		#region estamos en covertura?

		if (aiState == AIstate.GoToCover) {
			if(closestCover!=null){

				float distance=Vector3.Distance(transform.position,closestCover.transform.position);
				//Debug.Log("Distancia "+distance);
				if(distance <= 1.5f){
					//para animaciones de covertura

					aiState=AIstate.InCover;

				}
		}
		}
		#endregion
	}
Esempio n. 41
0
    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Floor")
        {
            if (state == AIstate.SUMMONED)
            {
                audioHandler.PlaySound("ImpactMetal_big");
                audioHandler.SwapMusicTrack(1);
                GameObject.Find("Main Camera").GetComponent<CameraShake>().InvokeShake(1.0F);
                state = AIstate.STOPPED;
                stateTimer = 2F;

                anim = GetComponentInChildren<Animator>();
            } else
            {
                GameObject.Find("Main Camera").GetComponent<CameraShake>().InvokeShake(.4F);
            }
        }
    }