Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Patrol.cs
- using UnityEngine;
- using UnityEngine.AI;
- using System.Collections;
- public enum RobotState
- {
- Idle,
- Patrol,
- Chase,
- Attack,
- }
- public class Patrol : MonoBehaviour
- {
- [SerializeField] private GameObject sight;
- public Transform[] points;
- private int destPoint = 0;
- private NavMeshAgent agent;
- public bool hasPlayerLock;
- private Transform player;
- private float switchTimer;
- [SerializeField] private float idleWaitTime = 3.0f;
- [SerializeField] private float attackTime = 1.0f;
- [SerializeField] private float attackDistance = 2.0f;
- public RobotState state;
- void Start()
- {
- state = RobotState.Idle;
- switchTimer = idleWaitTime;
- player = GameObject.FindGameObjectWithTag( "Player" ).transform;
- agent = GetComponent<NavMeshAgent>();
- // Disabling auto-braking allows for continuous movement
- // between points (ie, the agent doesn't slow down as it
- // approaches a destination point).
- agent.autoBraking = true;
- GotoNextPoint();
- }
- void GotoNextPoint()
- {
- // Returns if no points have been set up
- if( points.Length == 0 )
- return;
- // Set the agent to go to the currently selected destination.
- agent.destination = points[destPoint].position;
- // Choose the next point in the array as the destination,
- // cycling to the start if necessary.
- destPoint = ( destPoint + 1 ) % points.Length;
- }
- void Update()
- {
- switch( state )
- {
- case RobotState.Idle:
- switchTimer -= Time.deltaTime;
- agent.destination = transform.position;
- break;
- case RobotState.Attack:
- switchTimer -= Time.deltaTime;
- break;
- case RobotState.Chase:
- agent.destination = player.position;
- break;
- case RobotState.Patrol:
- if( !agent.pathPending && agent.remainingDistance < 0.5f )
- GotoNextPoint();
- break;
- default:
- break;
- }
- DetermineState();
- //Debug.Log( state + ", " + switchTimer );
- }
- private void DetermineState()
- {
- hasPlayerLock = sight.GetComponent<CombatantSight>().hasPlayerLock; // if the sight system has the player, so does the turret
- float dist = Vector3.Distance(player.position, transform.position );
- switch( state )
- {
- case RobotState.Idle:
- if( switchTimer < 0 )
- state = RobotState.Patrol;
- if( hasPlayerLock )
- state = RobotState.Chase;
- break;
- case RobotState.Attack:
- if( switchTimer < 0 )
- Attack();
- break;
- case RobotState.Chase:
- if( !hasPlayerLock )
- {
- state = RobotState.Idle;
- switchTimer = idleWaitTime;
- }
- if( dist < attackDistance )
- {
- state = RobotState.Attack;
- switchTimer = attackTime;
- }
- break;
- case RobotState.Patrol:
- if( hasPlayerLock )
- state = RobotState.Chase;
- break;
- default:
- break;
- }
- }
- private void Attack()
- {
- // Do Attack Stuff Here
- state = RobotState.Idle;
- switchTimer = idleWaitTime;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement