示例#1
0
    protected override void RpcChangeState(AI_STATE to)
    {
        base.RpcChangeState(to);

        if (GameManager.instance.GameState == GameState.GAME && gameObject.activeInHierarchy)
        {
            switch (to)
            {
            case AI_STATE.MOVE:
                agent.destination = lanePoints[destPoint];
                agent.isStopped   = false;
                break;

            case AI_STATE.WARNING:
                if (tmpTarget)
                {
                    agent.destination = tmpTarget.tfCache.position;
                }
                agent.isStopped = false;
                break;

            case AI_STATE.DISCOVER:
                agent.isStopped = true;
                break;
            }
        }
    }
示例#2
0
    public void StartState(AI_STATE _state)
    {
        StopAllCoroutines();

        switch (_state)
        {
        case AI_STATE.IDLE_STATE:
            StartCoroutine(IdleState());
            //StartCoroutine(CheckBattleModeCondition());
            break;

        case AI_STATE.PATROL_STATE:
            StartCoroutine(WaypointPatrolState());
            //StartCoroutine(CheckBattleModeCondition());
            break;

        case AI_STATE.RANDOM_WALK_STATE:
            StartCoroutine(RandomWalk());
            //StartCoroutine(CheckBattleModeCondition());
            break;

        case AI_STATE.BATTLE_STATE:
            StartCoroutine(BattleModeState());
            //StartCoroutine(CheckBattleModeCondition());
            break;
        }
    }
示例#3
0
    void CreateAI()
    {
        chaseState  = new ChaseState(this.gameObject);
        attackState = new AttackState(this.gameObject);

        currentState = AI_STATE.CHASE_STATE;
    }
示例#4
0
 // Use this for initialization
 void Start()
 {
     ai_state = AI_STATE.STOPPED;
     vxe = VoxelExtractionPointCloud.Instance;
     lastposition = new Vector3 ();
     init ();
 }
示例#5
0
 protected void ChangeState(AI_STATE to)
 {
     if (aiState != to && GameManager.instance.GameState == GameState.GAME && PhotonNetwork.isMasterClient)
     {
         photonView.RPC("RpcChangeState", PhotonTargets.AllViaServer, to);
     }
 }
示例#6
0
        // constructor
        public Enemy(Vector3 vel, Animation[] animations, string[] names, Vector3 loc, Rectangle rect, int value, int dir)
            : base(vel, animations, names, loc, rect)
        {
            // sets up commands
            commandQueue = new Queue<ICommand>();
            defaultCommands = new Queue<ICommand>();

            // sets starting location
            startLocation = loc;

            // sets enemy to be unaware of player
            state = AI_STATE.UNAWARE;

            center = new Vector3(rect.X + rect.Width, rect.Y + rect.Height, loc.Z);

            moneyValue = value;
            alive = true;
            direction = dir;

            switch (direction)
            {
                case 0: CurrentAnimation = "StandUp";
                    break;
                case 1: CurrentAnimation = "StandRight";
                    break;
                case 2: CurrentAnimation = "StandDown";
                    break;
                case 3: CurrentAnimation = "StandLeft";
                    break;
            }
        }
    // Start is called before the first frame update
    void Start()
    {
        currentState      = AI_STATE.HEALTH_HIGH;
        seekComponent     = GetComponent <KinematicSeek>();
        fleeComponent     = GetComponent <KinematicFlee>();
        arriveComponent   = GetComponent <KinematicArrive>();
        sidestepComponent = GetComponent <KinematicSidestep>();
        playerScript      = GetComponent <PlayerScript>();

        lowHealthTargetNearby = new TargetNearbyDecision(5.0f);
        lowHealthTargetNearIncomingProjectile = new IncomingProjectileDecision();
        lowHealthTargetFarIncomingProjectile  = new IncomingProjectileDecision();

        highHealthTargetNearby = new TargetNearbyDecision(5.0f);
        highHealthTargetNearIncomingProjectile = new IncomingProjectileDecision();
        highHealthTargetFarIncomingProjectile  = new IncomingProjectileDecision();

        arrivePlayerAction    = new ArrivePlayerAction();
        shootPlayerAction     = new ShootPlayerAction();
        seekHealthAction      = new SeekHealthAction();
        avoidPlayerAction     = new AvoidPlayerAction();
        avoidProjectileAction = new AvoidProjectileAction();

        avoidProjectileAction.kinematicComponent = seekComponent;
        avoidProjectileAction.character          = gameObject;
        arrivePlayerAction.kinematicComponent    = arriveComponent;
        arrivePlayerAction.character             = gameObject;
        seekHealthAction.kinematicComponent      = seekComponent;
        seekHealthAction.character           = gameObject;
        avoidPlayerAction.kinematicComponent = fleeComponent;
        avoidPlayerAction.character          = gameObject;
        shootPlayerAction.kinematicComponent = arriveComponent;
        shootPlayerAction.character          = gameObject;

        lowHealthTargetNearby.character   = gameObject;
        lowHealthTargetNearby.target      = target;
        lowHealthTargetNearby.trueBranch  = lowHealthTargetNearIncomingProjectile;
        lowHealthTargetNearby.falseBranch = lowHealthTargetFarIncomingProjectile;

        lowHealthTargetNearIncomingProjectile.character   = gameObject;
        lowHealthTargetNearIncomingProjectile.trueBranch  = avoidProjectileAction;
        lowHealthTargetNearIncomingProjectile.falseBranch = avoidPlayerAction;

        lowHealthTargetFarIncomingProjectile.character   = gameObject;
        lowHealthTargetFarIncomingProjectile.trueBranch  = avoidProjectileAction;
        lowHealthTargetFarIncomingProjectile.falseBranch = seekHealthAction;

        highHealthTargetNearby.character   = gameObject;
        highHealthTargetNearby.target      = target;
        highHealthTargetNearby.trueBranch  = highHealthTargetNearIncomingProjectile;
        highHealthTargetNearby.falseBranch = highHealthTargetFarIncomingProjectile;

        highHealthTargetNearIncomingProjectile.character   = gameObject;
        highHealthTargetNearIncomingProjectile.trueBranch  = avoidProjectileAction;
        highHealthTargetNearIncomingProjectile.falseBranch = shootPlayerAction;

        highHealthTargetFarIncomingProjectile.character   = gameObject;
        highHealthTargetFarIncomingProjectile.trueBranch  = avoidProjectileAction;
        highHealthTargetFarIncomingProjectile.falseBranch = arrivePlayerAction;
    }
示例#8
0
    private bool checkStateChangeValidity(AI_STATE newState)
    {
        bool result = false;

        switch(newState) {
        case AI_STATE.Idle:
            result = reachedPoint;
            break;
        case AI_STATE.MoveForward:
            if(reachedPoint && currentStateController.stateDelayTimer[(int)AI_STATE.MoveForward] < Time.time) {
                result = true;
            }
            break;
        case AI_STATE.MoveBackward:
            result = true;
            break;
        case AI_STATE.MoveLeft:
            result = true;
            break;
        case AI_STATE.MoveRight:
            result = true;
            break;
        case AI_STATE.MoveTopLeftDiagonal:
            result = true;
            break;
        case AI_STATE.MoveTopRightDiagonal:
            result = true;
            break;
        case AI_STATE.MoveBotLeftDiagonal:
            result = true;
            break;
        case AI_STATE.MoveBotRightDiagonal:
            result = true;
            break;
        case AI_STATE.Attacking:
            if(currentStateController.stateDelayTimer[(int)AI_STATE.Attacking] < Time.time) {
                result = true;
            }
            break;
        case AI_STATE.Jumping:
            result = true;
            break;
        case AI_STATE.Chasing:
            //if(player == null) {
                result = true;
            //}
            break;
        case AI_STATE.StopChasing:
            result = true;
            break;
        default:
            break;
        }

        return result;
    }
示例#9
0
 private void OnTriggerEnter(Collider other)
 {
     if (other.gameObject.tag == "Player" && curAiState == AI_STATE.IDLE)
     {
         targetPlayer    = other.gameObject;
         curAiState      = AI_STATE.CHASE;
         agent.isStopped = false;
         Debug.Log("Fire");
     }
 }
示例#10
0
    }  //공격

    //

    //가드
    IEnumerator Guard()
    {
        my_char.playerAni.SetBool("IsMove", true);
        my_char.playerAni.SetTrigger("IsMoveFirst");
        P2_AI.GetComponent <Player>().isGuard = true;
        yield return(new WaitForSeconds(randCount));

        P2_AI.GetComponent <Player>().isGuard = false;
        currentState   = AI_STATE.Idle;
        isActivieReady = false;
    }
示例#11
0
 // Use this for initialization
 void Start()
 {
     CoolDown               = 1.0f;
     initialPosition        = transform.position;
     OrderFromController    = false;
     TakePlayerPositionOnce = false;
     StandbySpeed           = 5.0f;
     AttackSpeed            = 50.0f;
     AttackTime             = 0.0f;
     AttackWeapon_State     = AI_STATE.IDLE_STATE;
 }
示例#12
0
 // Update is called once per frame
 void Update()
 {
     if (playerScript.health <= playerScript.LOW_HEALTH)
     {
         currentState = AI_STATE.HEALTH_LOW;
     }
     else
     {
         currentState = AI_STATE.HEALTH_HIGH;
     }
 }
    /// <summary>
    /// Get the new state for this ai based on the
    /// current world conditions
    /// </summary>
    /// <returns></returns>
    private AI_STATE GetNewAIState()
    {
        //Final state to return, default to returing the
        //current state
        AI_STATE returnState = currentAIState;

        //Check for LOS
        playerSeen = CanSeePlayer();

        //If we can see the player then instantly
        //change to chase the AI
        if (playerSeen)
        {
            return(AI_STATE.AI_STATE_SEEK_TO_PLAYER);
        }
        else
        {
            /*
             * Go through states if we are activly persuing the player
             * or the last know position and update if we should wander or
             * try to get to the players last know position
             */
            switch (currentAIState)
            {
            case AI_STATE.AI_STATE_SEEK_TO_PLAYER:
            {
                //We haven't seen the player this turn and are currently seeking the player
                //then we should now move to the last known pos
                returnState = AI_STATE.AI_STATE_SEEK_TO_LAST_POS;
                break;
            }

            case AI_STATE.AI_STATE_SEEK_TO_LAST_POS:
            {
                //If we are at the players last pos then switch to wander
                if (transform.position == lastKnownPlayerPos)
                {
                    returnState = AI_STATE.AI_STATE_WANDER;
                }
                break;
            }

            case AI_STATE.AI_STATE_WANDER:
            {
                //Don't need to change anything with wander just break
                break;
            }
            }
        }

        //No state change return the current state
        return(returnState);
    }
示例#14
0
    // Update is called once per frame
    void Update()
    {
        AIAnim.SetBool("isDead", isDead);

        if (isDead)
        {
            return;
        }

        switch (curAiState)
        {
        case AI_STATE.IDLE:
            for (int i = 0; i < 2; i++)
            {
                if (Vector3.Distance(GameManager.Instance.players[i].transform.position, transform.position) < 12)
                {
                    SetTarget(GameManager.Instance.players[i]);
                }
            }

            break;

        case AI_STATE.CHASE:
            agent.stoppingDistance = 5;
            if (Vector3.Distance(targetPlayer.transform.position, transform.position) > 5)
            {
                agent.SetDestination(targetPlayer.transform.position);
            }
            else
            {
                curAiState = AI_STATE.ATTACK;
            }
            break;

        case AI_STATE.ATTACK:
            curAiState = AI_STATE.RETURN;

            break;

        case AI_STATE.RETURN: agent.isStopped = false; targetPlayer = null; agent.stoppingDistance = 0; agent.SetDestination(originalPos); break;
        }

        if (curAiState == AI_STATE.RETURN)
        {
            //   Debug.Log(Vector3.Distance(transform.position, originalPos));
            if (Vector3.Distance(transform.position, originalPos) < 2f)
            {
                curAiState      = AI_STATE.IDLE;
                agent.isStopped = true;
            }
        }
    }
示例#15
0
    } //딜레이준뒤에

    IEnumerator Atk_Delay()
    {
        my_char.playerAni.SetTrigger("WeekPunch");
        yield return(new WaitForSeconds(0.3f));

        my_char.playerAni.SetBool("b_NextPunch", true);
        yield return(new WaitForSeconds(0.3f));

        my_char.playerAni.SetTrigger("IsIdle");
        my_char.playerAni.SetBool("b_NextPunch", false);
        currentState   = AI_STATE.Idle;
        isActivieReady = false;
    }  //공격
示例#16
0
 public void SetTarget(GameObject target)
 {
     if (target != null && curAiState == AI_STATE.IDLE)
     {
         targetPlayer    = target;
         curAiState      = AI_STATE.CHASE;
         agent.isStopped = false;
     }
     else if (target == null)
     {
         agent.isStopped = true;
     }
 }
示例#17
0
    //


    //일반공격
    IEnumerator Count()
    {
        currentState = AI_STATE.Atk;

        my_char.playerAni.SetTrigger("IsIdle");

        P2_AI.GetComponent <Player>().isGuard = true;

        yield return(new WaitForSeconds(randCount));

        P2_AI.GetComponent <Player>().isGuard = false;


        StartCoroutine("Atk_Delay");
    } //딜레이준뒤에
示例#18
0
    // Update is called once per frame
    void Update()
    {
        switch (AttackWeapon_State)
        {
        case AI_STATE.IDLE_STATE:
        {
            AttackWeapon_State = AI_STATE.STANDBY_STATE;
            break;
        }

        case AI_STATE.STANDBY_STATE:
        {
            if (TakePlayerPositionOnce == true)
            {
                AttackWeapon_State = AI_STATE.ATTACK_STATE;
            }
            break;
        }

        case AI_STATE.ATTACK_STATE:
        {
            if (transform.position.y <= PlayerDirection.y)
            {
                AttackWeapon_State = AI_STATE.AOE_ATTACK_STATE;
            }
            break;
        }

        case AI_STATE.AOE_ATTACK_STATE:
        {
            if (CoolDown <= 0.0f)
            {
                AttackWeapon_State = AI_STATE.DEAD_STATE;
            }
            break;
        }

        case AI_STATE.DEAD_STATE:
        {
            if (transform.position == initialPosition)
            {
                AttackWeapon_State = AI_STATE.IDLE_STATE;
            }
            break;
        }
        }
        UpdateAIState();
    }
示例#19
0
    // Valeur pour un all-sight vs alert sight en cas de poursuite
    // private float patrolAngle = 180f;
    // private float alertAngle = 22.5f;
    // private float patrolLength = 4.0f;
    // private float alertLength = 8.0f;
    public void Think()
    {
        if (status == AI_STATE.IDLE)
        {
            if (Sight(true))
            {
                testPNJMoves.Look(PlayerDirection());
            }
            if (Random.Range(0, 300) == 1)
            {
                testPNJMoves.Look((Random.Range(0, 3) <= 1));
                status = AI_STATE.PATROL;
            }
        }
        else if (status == AI_STATE.PATROL)
        {
            if (GroundCheck(true))
            {
                testPNJMoves.Move(testPNJMoves.patrolSpeed, testPNJMoves.isRight);
            }
            else
            {
                status = AI_STATE.IDLE;
                testPNJMoves.anim.SetBool("isRunning", false);
            }

            if (Random.Range(0, 120) == 1)
            {
                status = AI_STATE.IDLE;
                testPNJMoves.anim.SetBool("isRunning", false);
            }
        }
        // PAS D'ALERTE SUR LES PNJ POUR L'INSTANT MAIS COMPORTEMENT SIMILAIRE AU COMBAT CLASSIQUE !
        else if (status == AI_STATE.ALERT)
        {
            testPNJMoves.Look(PlayerDirection());
            if (GroundCheck(true))
            {
                testPNJMoves.Move(testPNJMoves.speed, testPNJMoves.isRight);
            }
            currentAlertTime += 1;
            if (currentAlertTime >= alertTime)
            {
                status           = AI_STATE.IDLE;
                currentAlertTime = 0;
            }
        }
    }
示例#20
0
    // Use this for initialization
    void Start()
    {
        ai_state = AI_STATE.STOPPED;
        vxe      = VoxelExtractionPointCloud.Instance;
        if (camera == null)
        {
            camera = vxe.camera;
        }

        itemspawn           = ItemSpawner.Instance;
        lastposition        = new Vector3();
        stepdownThreshold   = vxe.voxel_size * 2;
        stepdownThreshold   = stepdownThreshold * stepdownThreshold;
        playerFaceThreshold = vxe.voxel_size * 5;
        //init ();
    }
    private void Start()
    {
        //Init current state to wander, as we don't know if we
        //can see the player when we start
        currentAIState = AI_STATE.AI_STATE_WANDER;

        //Init Target Pos and prev target to be our current position
        prevTargetPos = targetPos = transform.position;

        //Get required pathfinding component
        pathfinder = GetComponent <AIPathfinding>();

        //Find the player object if there is not one already assigned
        if (playerObject == null)
        {
            playerObject = FindObjectOfType <PlayerData>().gameObject;
        }
    }
示例#22
0
文件: EnemyAi.cs 项目: NickHiga/Lurk
		// Use this for initialization
		void Awake()
		{
			enemySight = GetComponent<EnemySight2>();
			nav = GetComponent<NavMeshAgent>();
			player = GameObject.FindGameObjectWithTag("Player").transform;
			audioSource = GetComponent<AudioSource>();
			globalLastPlayerSighting = GameObject.FindGameObjectWithTag("GM").GetComponent<LastPlayerSighting>();
			character = GetComponent<ThirdPersonCharacter>();
			playerScript = player.GetComponent<Player>();

			nav.updatePosition = true;
			nav.updateRotation = false;

			currentState = AI_STATE.PATROLLING;
			animator = GetComponent<Animator>();

			nextShotDelay = 0.0f;
		}
示例#23
0
    //

    //점프
    IEnumerator Jump()
    {
        Vector3 moveVec3 = my_char.myRb.velocity;

        if (P2_AI.transform.position.x > 7.5f || P2_AI.transform.position.x < -7.5f)
        {
            moveVec3 = new Vector3(GetMoveSpeed() * Time.deltaTime, 10, 0); // 기본 값 * 점프력
        }
        else
        {
            moveVec3 = new Vector3(-GetMoveSpeed() * Time.deltaTime, 10, 0); // 기본 값 * 점프력
        }

        my_char.myRb.velocity = (moveVec3);
        yield return(new WaitForSeconds(2f));

        currentState   = AI_STATE.Idle;
        isActivieReady = false;
    }
示例#24
0
 // Update is called once per frame
 void Update()
 {
     if (aiSettings.triggered)
     {
         ai.update();
         AI_STATE nextstate = ai.nextstate();
         if (aistate != nextstate)
         {
             if (nextstate == AI_STATE.Attack)
             {
                 ai = new AIAttack(ref aiSettings, transform, ref agent);
             }
             else if (nextstate == AI_STATE.Chase)
             {
                 ai = new AIChase(ref aiSettings, transform, ref agent);
             }
             else if (nextstate == AI_STATE.Wait)
             {
                 ai = new AIWait(ref aiSettings, transform, ref agent);
             }
             else if (nextstate == AI_STATE.Patrol)
             {
                 ai = new AIPatrol(ref aiSettings, transform, ref agent);
             }
             else if (nextstate == AI_STATE.ReturnToPatrol)
             {
                 ai = new AIReturnToPatrol(ref aiSettings, transform, ref agent);
             }
             aistate      = nextstate;
             ai.lastKnown = lk;
         }
         lk       = ai.lastKnown;
         DebugaiS = aistate;
         DebugaiT = aiSettings.type;
         //Debug.DrawLine(lk - Vector3.right * 0.5f, lk + Vector3.right * 0.5f, Color.red);
         //Debug.DrawLine(lk - Vector3.forward * 0.5f, lk + Vector3.forward * 0.5f, Color.blue);
         //Debug.DrawLine(lk - Vector3.up * 0.5f, lk + Vector3.up * 0.5f, Color.green);
     }
 }
示例#25
0
 public void time()
 {
     timer++;
     if (ai_state != AI_STATE.FRIGHTENED)
     {
         if (timer == 800)
         {
             ai_state = AI_STATE.CHASE;
             reverseDirection();
         }
         if (timer == 2000)
         {
             ai_state = AI_STATE.SCATTER;
             reverseDirection();
             timer = 0;
         }
     }
     else
     {
         //frightened.
     }
 }
示例#26
0
 public AIBehaviour(AI_STATE _state)
 {
     state = _state;
     positionData = Vector3.zero;
 }
示例#27
0
文件: EnemyAi.cs 项目: NickHiga/Lurk
		void Shooting()
		{
			nav.Stop();
			character.Move(Vector3.zero, false, false);
			transform.rotation = Quaternion.Slerp(transform.rotation,
				Quaternion.LookRotation(enemySight.personalLastSighting - transform.position),
				nav.angularSpeed * Time.deltaTime);

			// If the player is not in shooting range, and also
			// the AI is not in the middle of firing a shot.
			if (!IsPlayerInShootingRange() && shootingTimer == 0)
			{
				currentState = AI_STATE.CHASING;
			}
			else
			{
				shootingTimer += Time.deltaTime;
				if (shootingTimer >= nextShotDelay)
				{
					shootingTimer = 0.0f;
					audioSource.PlayOneShot(shootingSound, 1.0f);

					if (!firstShotFired)
					{
						firstShotFired = true;
						nextShotDelay = timeBetweenShots + Random.Range(-shootingTimeVariance, shootingTimeVariance);
					}

					if (Random.Range(0.0f, 1.0f) <= shootingHitChance // If we are within the random shot chance,
																      // the player will be hit.
						&& IsPlayerInShootingRange()) // This is to make sure that the player is not behind
													  // a wall when the bullet is actually shot.
					{
						nextShotDelay = timeBetweenShots + Random.Range(-shootingTimeVariance, shootingTimeVariance);
						playerScript.TakeDamage(damageDone);
					}
				}	
			}
		}
示例#28
0
 public void SetCurrentState(AI_STATE _state)
 {
     currentAi_State = _state;
 }
示例#29
0
 public void init()
 {
     ai_state = AI_STATE.MOVING;
     StartCoroutine(moveit());
 }
示例#30
0
    private void onPlayerDetected(AI_STATE newState, GameObject go)
    {
        if(player != go) {
            player = go;
        }

        onStateChanged(newState);
    }
示例#31
0
 private void firePlayerDetectedEvent(AI_STATE newState, GameObject go)
 {
     if(playerDetectedHandlerEvent != null) {
         playerDetectedHandlerEvent(newState, go);
     }
 }
示例#32
0
    Vector3 getNextMoveLimited()
    {
        Vector3 targetPosition = camera.transform.position;
        ai_target = AI_TARGET.PLAYER;

        if (tag == "Pet")
        {
            for (int i=0; i<itemspawn.items.Length; i++)
            {
                if (itemspawn.spawneditems [i] == null || itemspawn.spawneditems [i].GetComponent<TriggerScript> ().triggered)
                    continue;

                float groundLength = (itemspawn.spawneditems [i].transform.position - transform.position).magnitude;
                if (groundLength < vxe.voxel_size * 15)
                {
                    targetPosition = itemspawn.spawneditems [i].transform.position;
                    ai_target = AI_TARGET.SHEEP;
                    break;
                }
            }
        }

        Vector3 rawdir = Vector3.ProjectOnPlane ((targetPosition - transform.position), Vector3.up);
        Vector3 dir = rawdir.normalized;

        //Debug.Log ( "dist: " + rawdir.magnitude + " " + playerFaceThreshold);

        if(ai_target == AI_TARGET.PLAYER && rawdir.magnitude < playerFaceThreshold)
        {
            ai_state = AI_STATE.STOPPED;
            return dir;
        }

        Vector3 coords = Vector3.zero;
        Vector3 norm = Vector3.zero;
        bool notgrounded = false;

        bool hit = vxe.GroundedRayCast (transform.position, dir, STEP, ref coords, ref norm, ref notgrounded, 0.5f);

        Vector3 jumpDir = Vector3.zero;
        bool canJump = checkForJumpPositions (dir, out jumpDir);
        float jumpPositionToTarget = (jumpPosition - targetPosition).sqrMagnitude;
        float movePositionToTarget = (coords - targetPosition).sqrMagnitude;

        if(canJump && jumpPositionToTarget < movePositionToTarget)
        {
            ai_state = AI_STATE.JUMPING;
            return jumpDir;
        }

        if(!hit)
        {
            if(notgrounded)
            {
                bool isThereGround = vxe.RayCast (coords, Vector3.down, BIG_STEP, ref fallPosition, ref norm, 0.5f);
                if(isThereGround)
                {
                    fallPosition += Vector3.up * vxe.voxel_size * 0.5f;
                    ai_state = AI_STATE.FALLING;
                    return dir;
                }
            }
            else
            {
                movePosition = coords;
                ai_state = AI_STATE.MOVING;
                return dir;
            }
        }
        else
        {
            bool isThereSurface = vxe.OccupiedRayCast (coords, Vector3.up, JUMP_RANGE, ref jumpPosition, ref norm);
            if(isThereSurface)
            {
                jumpPosition -= Vector3.up * vxe.voxel_size * 0.5f;
                ai_state = AI_STATE.JUMPING;
                return dir;
            }
        }

        ai_state = AI_STATE.STOPPED;
        return dir;
    }
示例#33
0
    Vector3 getNextMoveLimited()
    {
        Vector3 targetPosition = camera.transform.position;

        ai_target = AI_TARGET.PLAYER;

        /*
         * if (tag == "Pet") {
         *      for (int i=0; i<itemspawn.items.Length; i++) {
         *              if (itemspawn.spawneditems [i] == null || itemspawn.spawneditems [i].GetComponent<TriggerScript> ().triggered)
         *                      continue;
         *
         *              float groundLength = (itemspawn.spawneditems [i].transform.position - transform.position).magnitude;
         *              if (groundLength < vxe.voxel_size * 20) {
         *                      targetPosition = itemspawn.spawneditems [i].transform.position;
         *                      ai_target = AI_TARGET.SHEEP;
         *                      break;
         *              }
         *      }
         * }
         */
        Vector3 camtome = (targetPosition - transform.position);
        Vector3 rawdir  = Vector3.ProjectOnPlane(camtome, Vector3.up);
        Vector3 dir     = rawdir.normalized;

        if (ai_target == AI_TARGET.PLAYER && rawdir.magnitude < playerFaceThreshold)
        {
            ai_state = AI_STATE.STOPPED;
            return(dir);
        }

        Vector3 coords      = Vector3.zero;
        Vector3 norm        = Vector3.zero;
        bool    notgrounded = false;

        bool hit = vxe.GroundedRayCast(transform.position, dir, STEP, ref coords, ref norm, ref notgrounded, 0.5f);


        Vector3 jumpDir = Vector3.zero;
        bool    canJump = checkForJumpPositions(dir, out jumpDir);
        float   jumpPositionToTarget = (jumpPosition - targetPosition).sqrMagnitude;
        float   movePositionToTarget = (coords - targetPosition).sqrMagnitude;



        if (!hit)
        {
            if (canJump && jumpPositionToTarget < movePositionToTarget)
            {
                ai_state = AI_STATE.JUMPING;
                return(jumpDir);
            }

            if (notgrounded)
            {
                bool isThereGround = vxe.RayCast(coords, Vector3.down, BIG_STEP, ref fallPosition, ref norm, 0.5f);
                if (isThereGround)
                {
                    fallPosition += Vector3.up * vxe.voxel_size * 0.5f;
                    ai_state      = AI_STATE.FALLING;
                    return(dir);
                }
            }
            else
            {
                movePosition = coords;
                ai_state     = AI_STATE.MOVING;
                return(dir);
            }
        }
        else
        {
            bool isThereSurface = vxe.OccupiedRayCast(coords, Vector3.up, BIG_STEP, ref jumpPosition, ref norm);
            if (isThereSurface)
            {
                jumpPosition -= Vector3.up * vxe.voxel_size * 0.5f;
                ai_state      = AI_STATE.JUMPING;
                return(dir);
            }
        }

        ai_state = AI_STATE.STOPPED;
        return(dir);
    }
示例#34
0
 public void init()
 {
     ai_state = AI_STATE.MOVING;
     StartCoroutine (moveit ());
 }
示例#35
0
 // Use this for initialization
 void Start()
 {
     ai_state = AI_STATE.STOPPED;
     vxe = VoxelExtractionPointCloud.Instance;
     itemspawn = ItemSpawner.Instance;
     lastposition = new Vector3 ();
     stepdownThreshold = vxe.voxel_size * 2;
     stepdownThreshold = stepdownThreshold * stepdownThreshold;
     playerFaceThreshold = vxe.voxel_size * 7;
     //init ();
 }
示例#36
0
    Vector3 getNextMove()
    {
        Vector3 coords = Vector3.zero;
        Vector3 norm = Vector3.zero;
        bool notgrounded = false;

        Vector3 dir = Vector3.ProjectOnPlane((camera.transform.position - transform.position),Vector3.up).normalized;
        bool hit = vxe.GroundedRayCast (transform.position, dir, STEP, ref coords, ref norm, ref notgrounded, 0.5f);

        if(!hit)
        {
            if(notgrounded)
            {
                bool isThereGround = vxe.RayCast (coords, Vector3.down, BIG_STEP, ref fallPosition, ref norm, 0.5f);
                if(isThereGround)
                {
                    fallPosition += Vector3.up * vxe.voxel_size * 0.5f;
                    ai_state = AI_STATE.FALLING;
                    return dir;
                }
            }
            else
            {
                    movePosition = coords;
                    ai_state = AI_STATE.MOVING;
                    return dir;
            }
        }
        else
        {
            bool isThereSurface = vxe.OccupiedRayCast (coords, Vector3.up, BIG_STEP, ref jumpPosition, ref norm);
            //bool ICannotJump = vxe.CheapRayCast(transform.position,Vector3.up, 5);
            if(isThereSurface)
            {
                jumpPosition -= Vector3.up * vxe.voxel_size * 0.5f;
                ai_state = AI_STATE.JUMPING;
                return dir;
            }
        }

        ai_state = AI_STATE.STOPPED;
        return Vector3.zero;
    }
示例#37
0
 public void SetState(AI_STATE _newState)
 {
     currentState = _newState;
 }
    /// <summary>
    /// Work out the new state for the AI to be in
    /// </summary>
    /// <returns>New State</returns>
    private void UpdateAI(GameStateManager.GameTurn newTurn)
    {
        //If it is not our turn then return
        if (newTurn != GameStateManager.GameTurn.TURN_AI)
        {
            return;
        }

        //Null Check Player and early out
        if (!playerObject)
        {
            return;
        }

        //Get a new state, based on current conditions
        currentAIState = GetNewAIState();

        //Set the prev target pos to the current pos,
        //so we can check if the target pos hasn't moved
        prevTargetPos = targetPos;

        switch (currentAIState)
        {
        case AI_STATE.AI_STATE_SEEK_TO_PLAYER:
        {
            //Set our target position to be the player
            targetPos = playerObject.transform.position;
            //Update the last known player position, set it to our y pos
            //as neither object moves in the y direction
            lastKnownPlayerPos = new Vector3(targetPos.x, transform.position.y, targetPos.z);
            break;
        }

        case AI_STATE.AI_STATE_SEEK_TO_LAST_POS:
        {
            //Set the target pos to the players
            //last know position
            targetPos = lastKnownPlayerPos;

            break;
        }

        case AI_STATE.AI_STATE_WANDER:
        {
            //Find a point on the map that we should
            //go to, then set it as our target pos
            targetPos = GetWanderTargetPos();
            break;
        }
        }

        //If the target pos is not the same as the previous
        //and it is not the current pos
        //target pos find a route to the target
        if (targetPos != prevTargetPos && targetPos != transform.position)
        {
            lastPathfindResults = pathfinder.GetAStarPath(transform.position, targetPos);
        }

        //Check that we have a path to follow
        if (lastPathfindResults.Count > 0)
        {
            //Get the next pos from the list and keep our y the same
            //because the grid is flat to the x/z plane
            Vector3 nextPos = lastPathfindResults[0].transform.position;
            nextPos.y = transform.position.y;

            //Rotate and move towards next position
            transform.LookAt(nextPos);

            //Check that the tile at the next pos is not occupied by the player
            WalkableTile nextTile = lastPathfindResults[0].GetComponentInChildren <WalkableTile>();
            if (nextTile)
            {
                if (!nextTile.IsOccupied || nextTile.Occupier.GetComponent <PlayerMovement>())
                {
                    //Attempt to reserve the space and only move if we do this succcessfully
                    if (nextTile.AttemptToReserve(this.gameObject))
                    {
                        StartCoroutine(MoveOverTime(nextPos, turnDuration));
                    }
                }
            }

            //Remove the pos from the list so we don't
            //visit it again
            lastPathfindResults.RemoveAt(0);
        }

        //Debug Test for State
        Debug.Log("FOX :: " + currentAIState.ToString());

        //End the turn after turn timer is up - call event
        StartCoroutine(EndTurnAfterTime(GameStateManager.GameTurn.TURN_AI, turnDuration));
    }
示例#39
0
文件: EnemyAi.cs 项目: NickHiga/Lurk
		void Chasing()
		{
			//if (!enemySight.playerInSight)
			// if (all AI Lost sight of player)
			// currentState = AI_STATE.SEARCHING;
			// if (in shooting range and in line of sight)
			// currentState = AI_STATE.SHOOTING
			// else
			// currentState = AI_STATE.CHASING
			Vector3 sightingDeltaPos = enemySight.personalLastSighting - transform.position;
			if (sightingDeltaPos.sqrMagnitude >= 4f)
			{
				nav.SetDestination(enemySight.personalLastSighting);
			}

			nav.Resume();
			nav.speed = chaseSpeed;
			character.Move(nav.desiredVelocity, false, false);

			if (nav.remainingDistance <= nav.stoppingDistance)
			{
				chaseTimer += Time.deltaTime;
				if (chaseTimer >= ChaseWaitTime)
				{
					globalLastPlayerSighting.pos = globalLastPlayerSighting.resetPosition;
					enemySight.personalLastSighting = globalLastPlayerSighting.resetPosition;
					chaseTimer = 0f;
					currentState = AI_STATE.PATROLLING;
				}
			}
			else
				chaseTimer = 0f;

			if (IsPlayerInShootingRange())
				currentState = AI_STATE.SHOOTING;
		}
示例#40
0
 void ReturnToPatrol()
 {
     curAiState = AI_STATE.RETURN;
 }
示例#41
0
文件: EnemyAi.cs 项目: NickHiga/Lurk
		public void SetHealth(float newHealth)
		{
			health = newHealth;
			// CHANGE THIS LATER
			currentState = AI_STATE.CHASING;
			enemySight.personalLastSighting = player.transform.position;
			globalLastPlayerSighting.AlertOtherAI();

			if (health <= 0)
			{
				currentState = AI_STATE.DEAD;

				if (!isDeathSoundPlaying)
				{
					audioSource.PlayOneShot(deathSound, 1.0f);
					isDeathSoundPlaying = true;
				}
			}
		}
示例#42
0
 /// <summary>
 /// Switches the state of the current pursuit to a given state
 /// </summary>
 /// <param name="state">state to switch the pursuit to</param>
 private void SwitchPursuitState(AI_STATE state)
 {
     //For every enemy in the pursuit, change their state to the new state and have them get new commands.
     foreach (Enemy enemy in currentPursuit)
     {
         enemy.commandQueue.Clear();
         enemy.currentCommand = null;
         enemy.state = state;
     }
     //If we are switching to hunting, begin the hunt.
     if (state == AI_STATE.HUNTING)
     {
         BeginHunt();
     }
     //If the enemy state is no longer hunting, end the current pursuit.
     if (state < AI_STATE.HUNTING)
         isPursuitActive = false;
 }
示例#43
0
文件: EnemyAi.cs 项目: NickHiga/Lurk
		public void SetState(AI_STATE newState)
		{
			currentState = newState;
		}
示例#44
0
    public void Think()
    {
        if (Sight(true))
        {
            status           = AI_STATE.ALERT;
            currentAlertTime = 0;
        }

        if (status == AI_STATE.IDLE)
        {
            if (Random.Range(0, 180) == 1)
            {
                testEnemyMoves.isRight = !testEnemyMoves.isRight;
                status = AI_STATE.PATROL;
            }
        }
        else if (status == AI_STATE.PATROL)
        {
            if (GroundCheck(true))
            {
                testEnemyMoves.Move(testEnemyMoves.patrolSpeed, testEnemyMoves.isRight);
            }
            else
            {
                status = AI_STATE.IDLE;
                testEnemyMoves.isRunning = false;
            }
        }
        else if (status == AI_STATE.ALERT)
        {
            testEnemyMoves.isRight = PlayerDirection();
            if (testEnemyMoves.isAttacking == false)
            {
                if (Vector3.Distance(transform.position, player.transform.position) <= 1.5)
                {
                    testEnemyMoves.isAttacking = true;
                    testEnemyMoves.isRunning   = false;
                    if (!hasAtt)
                    {
                        hasAtt = true;
                        FindObjectOfType <PlayerController>().Damage(3);
                        actor.anim.SetBool("isAttacking", testEnemyMoves.isAttacking);
                    }
                }
                else if (GroundCheck(true))
                {
                    testEnemyMoves.Move(testEnemyMoves.speed, testEnemyMoves.isRight);
                }
            }
            else
            {
                if (actor.anim.GetBool("isAttacking") == false)
                {
                    testEnemyMoves.isAttacking = false;
                }
            }
            currentAlertTime += 1;
            if (currentAlertTime >= alertTime)
            {
                status           = AI_STATE.IDLE;
                currentAlertTime = 0;
            }
        }
        actor.anim.SetBool("isRunning", testEnemyMoves.isRunning);
    }
示例#45
0
    private void onStateChanged(AI_STATE newState)
    {
        if(dead) return;

        if(currentState == newState) {
            return;
        }

        if(!checkStateChangeValidity(newState)) {
            return;
        }

        if(!checkStateTransitionValidity(newState)) {
            return;
        }

        switch(newState) {
        case AI_STATE.Idle:
            playerAnim.playIdleAnimation();
            break;
        case AI_STATE.MoveForward:
            playerAnim.playMoveForwardAnimation();
            currentStateController.stateDelayTimer[(int)AI_STATE.MoveForward] = Time.time + 10.0f;
            break;
        case AI_STATE.MoveBackward:
            playerAnim.playMoveBackwardAnimation();
            break;
        case AI_STATE.MoveLeft:
            playerAnim.playMoveForwardAnimation();
            break;
        case AI_STATE.MoveRight:
            playerAnim.playMoveForwardAnimation();
            break;
        case AI_STATE.MoveTopLeftDiagonal:
            playerAnim.playMoveForwardAnimation();
            break;
        case AI_STATE.MoveTopRightDiagonal:
            playerAnim.playMoveForwardAnimation();
            break;
        case AI_STATE.MoveBotLeftDiagonal:
            playerAnim.playMoveBackwardAnimation();
            break;
        case AI_STATE.MoveBotRightDiagonal:
            playerAnim.playMoveBackwardAnimation();
            break;
        case AI_STATE.Attacking:
            playerAnim.playIdleAnimation();
            playerAnim.playAttackAnimation();
            currentStateController.stateDelayTimer[(int)AI_STATE.Attacking] = Time.time + fireRate;
            break;
        case AI_STATE.Jumping:
            playerAnim.playJumpAnimation();
            currentStateController.stateDelayTimer[(int)AI_STATE.Jumping] = Time.time + 1.0f;
            break;
        case AI_STATE.Chasing:
            playerAnim.playMoveForwardAnimation();
            break;
        case AI_STATE.StopChasing:
            playerAnim.playIdleAnimation();
            player = null;
            reachedPoint = true;
            break;
        default:
            break;
        }

        currentState = newState;
    }
示例#46
0
 public AIBehaviour(AI_STATE _state, Vector3 _positionData, float _stoppingDistance)
 {
     state = _state;
     positionData = _positionData;
     floatData = _stoppingDistance;
 }
示例#47
0
    private bool checkStateTransitionValidity(AI_STATE newState)
    {
        bool result = false;

        switch(currentState) {
        case AI_STATE.Idle:
            result = true;
            break;
        case AI_STATE.MoveForward:
            result = true;
            break;
        case AI_STATE.MoveBackward:
            result = true;
            break;
        case AI_STATE.MoveLeft:
            result = true;
            break;
        case AI_STATE.MoveRight:
            result = true;
            break;
        case AI_STATE.MoveTopLeftDiagonal:
            result = true;
            break;
        case AI_STATE.MoveTopRightDiagonal:
            result = true;
            break;
        case AI_STATE.MoveBotLeftDiagonal:
            result = true;
            break;
        case AI_STATE.MoveBotRightDiagonal:
            result = true;
            break;
        case AI_STATE.Attacking:
            result = true;
            break;
        case AI_STATE.Jumping:
            result = true;
            break;
        case AI_STATE.Chasing:
            result = true;
            break;
        case AI_STATE.StopChasing:
            result = true;
            break;
        default:
            break;
        }

        return result;
    }
示例#48
0
 private void fireStateChangeEvent(AI_STATE newState)
 {
     if(playerStateHandlerEvent != null) {
         playerStateHandlerEvent(newState);
     }
 }
示例#49
0
    void Update_Default_Statement()
    {
        if (currentState == AI_STATE.Atk ||
            currentState == AI_STATE.Guard ||
            currentState == AI_STATE.Back_Jump ||
            currentState == AI_STATE.Wait_Attack ||
            currentState == AI_STATE.Gather_Atk)
        {
            return;
        }

        if (GetDistance() > 8.5f)
        {
            if (currentState != AI_STATE.Dash)
            {
                currentState = AI_STATE.Dash;
                my_char.playerAni.SetTrigger("IsDashFirst");
            }
        }
        else if (GetDistance() > 4.5f)
        {
            //if (isActivieReady)
            //    return;
            if (currentState == AI_STATE.Walk) //밑에랑중복
            {
                return;
            }
            int RandNum = Random.Range(0, 3);

            switch (RandNum)
            {
            case 0:
                if (currentState != AI_STATE.Walk)
                {
                    my_char.playerAni.SetBool("IsMove", true);
                    my_char.playerAni.SetTrigger("IsMoveFirst");
                    currentState = AI_STATE.Walk;
                }
                break;

            case 1:
                if (currentState != AI_STATE.Back_Jump)
                {
                    currentState = AI_STATE.Back_Jump;
                    my_char.playerAni.SetBool("IsJumpFirst", true);
                    my_char.playerAni.SetBool("IsJump", true);
                    StartCoroutine(Jump());
                    isActivieReady = true;
                }
                break;

            case 2:
                if (currentState != AI_STATE.Wait_Attack)
                {
                    currentState = AI_STATE.Wait_Attack;

                    isActivieReady = true;
                    StartCoroutine(Wait_Attack());
                }
                break;
            }
        }
        else
        {
            //if (isActivieReady)
            //    return;

            int RandNum = Random.Range(0, 3);
            Debug.Log("asdasds" + RandNum);
            switch (RandNum)
            {
            case 0:
                if (currentState != AI_STATE.Gather_Atk)
                {
                    currentState = AI_STATE.Gather_Atk;

                    randCount      = Random.Range(0.01f, 0.3f);
                    isActivieReady = true;
                    StartCoroutine(Count());
                }
                break;

            case 1:
                if (currentState != AI_STATE.Guard)
                {
                    currentState = AI_STATE.Guard;

                    randCount      = Random.Range(0.5f, 0.9f);
                    isActivieReady = true;
                    StartCoroutine(Guard());
                }
                break;

            case 2:
                if (currentState != AI_STATE.Wait_Attack)
                {
                    currentState = AI_STATE.Wait_Attack;

                    isActivieReady = true;
                    StartCoroutine(Wait_Attack());
                }
                break;
            }
        }
    }
示例#50
0
文件: EnemyAi.cs 项目: NickHiga/Lurk
		void Patrolling()
		{
			// if (playerInSight)
			// currentState = AI_STATE.CHASING;
			// if (sound made)
			// currentState = AI_STATE.SEARCHING;
			nav.Resume();
			nav.speed = patrolSpeed;
			if (nav.destination == globalLastPlayerSighting.resetPosition || nav.remainingDistance < nav.stoppingDistance)
			{
				patrolTimer += Time.deltaTime;
				if (patrolTimer >= patrolWaitTime)
				{
					if (wayPointInd == patrolWayPoints.Length - 1)
					{
						wayPointInd = 0;
					}
					else
					{
						wayPointInd++;
					}

					patrolTimer = 0f;
				}
			}
			else
			{
				patrolTimer = 0f;
			}

			nav.SetDestination(patrolWayPoints[wayPointInd].position);
			character.Move(nav.desiredVelocity, false, false);

			if (enemySight.playerInSight && !playerScript.IsDead())
			{
				currentState = AI_STATE.CHASING;
				globalLastPlayerSighting.AlertOtherAI();
			}
		}
示例#51
0
    Vector3 getNextMove()
    {
        Vector3 coords      = Vector3.zero;
        Vector3 norm        = Vector3.zero;
        bool    notgrounded = false;

        Vector3 targetPosition = camera.transform.position;

        ai_target = AI_TARGET.PLAYER;

        /*
         * if (tag == "Pet") {
         *      for (int i=0; i<itemspawn.items.Length; i++) {
         *              if (itemspawn.spawneditems [i] == null || itemspawn.spawneditems [i].GetComponent<TriggerScript> ().triggered)
         *                      continue;
         *
         *              float groundLength = (itemspawn.spawneditems [i].transform.position - transform.position).magnitude;
         *              if (groundLength < vxe.voxel_size * 20) {
         *                      targetPosition = itemspawn.spawneditems [i].transform.position;
         *                      ai_target = AI_TARGET.SHEEP;
         *                      break;
         *              }
         *      }
         * }
         */
        Vector3 rawdir = Vector3.ProjectOnPlane((targetPosition - transform.position), Vector3.up);
        Vector3 dir    = rawdir.normalized;

        //Debug.Log ( "dist: " + rawdir.magnitude + " " + playerFaceThreshold);

        if (ai_target == AI_TARGET.PLAYER && rawdir.magnitude < playerFaceThreshold)
        {
            ai_state = AI_STATE.STOPPED;
            return(dir);
        }

        bool hit = vxe.GroundedRayCast(transform.position, dir, STEP, ref coords, ref norm, ref notgrounded, 0.5f);

        if (!hit)
        {
            if (notgrounded)
            {
                bool isThereGround = vxe.RayCast(coords, Vector3.down, BIG_STEP, ref fallPosition, ref norm, 0.5f);
                if (isThereGround)
                {
                    fallPosition += Vector3.up * vxe.voxel_size * 0.5f;
                    ai_state      = AI_STATE.FALLING;
                    return(dir);
                }
            }
            else
            {
                movePosition = coords;
                ai_state     = AI_STATE.MOVING;
                return(dir);
            }
        }
        else
        {
            bool isThereSurface = vxe.OccupiedRayCast(coords, Vector3.up, BIG_STEP, ref jumpPosition, ref norm);
            //bool ICannotJump = vxe.CheapRayCast(transform.position,Vector3.up, 5);
            if (isThereSurface)
            {
                jumpPosition -= Vector3.up * vxe.voxel_size * 0.5f;
                ai_state      = AI_STATE.JUMPING;
                return(dir);
            }
        }

        ai_state = AI_STATE.STOPPED;
        return(Vector3.zero);
    }
示例#52
0
 public AIBehaviour(AI_STATE _state, float _timerData)
 {
     state = _state;
     floatData = _timerData;
 }