// Use this for initialization protected virtual void Start() { model = GetComponent <GenericShipModel>(); view = GetComponent <GenericShipView>(); _myDetector = GetComponent <SphereDetector>(); if (_myDetector == null) { Debug.LogError("No Detector attached to " + gameObject + "!"); } // Check if initial state is specified. If not, and there is no waypoint manager, then begin in square patrol mode. // Otherwise, begin in waypoint patrol mode. if (_startState == GenericShipAiState.Idle && _waypointManager == null) { _currentState = GenericShipAiState.SquarePatrolling; } if (_startState == GenericShipAiState.Idle && _waypointManager != null) { _currentState = GenericShipAiState.WaypointPatrolling; } // If we are patrolling and have no waypoints, then begin patrolling in square formation. if (_currentState == GenericShipAiState.SquarePatrolling) { StartCoroutine(SquareFormationPatrol()); } // Begin custom update loop for AI. InvokeRepeating(nameof(UpdateAiController), 0.0f, _behaviorChangeRate); }
// Updates the AI controller. private void UpdateAiController() { if (_currentState == GenericShipAiState.SquarePatrolling) { // If we are in square formation patrol and have reached our current forward point, then turn left and generate a new forward point. if (transform.position == _forwardSquarePatrolPoint) { // Turn some number of degrees left. transform.Rotate(new Vector3(0, 0, Random.Range(0, 90))); StartCoroutine(SquareFormationPatrol()); } } // Check if there is an enemy within range. var closestEnemy = _myDetector.ClosestEnemy(); // If we have an enemy, then chase and attack it. Otherwise, resume patrolling. // Don't execute this if we're in lock chase if (closestEnemy != null && !_lockedInChase) { _currentState = GenericShipAiState.Chasing; StartCoroutine(LockChase()); StartCoroutine(ChaseAttackEnemyVariance()); StartCoroutine(ChaseAttackEnemy(closestEnemy)); } else if (closestEnemy == null) { if (_waypointManager != null) { _currentState = GenericShipAiState.WaypointPatrolling; } _currentState = GenericShipAiState.SquarePatrolling; } }