Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class AIBehaviour : MonoBehaviour
- {
- public enum AIState
- {
- Going, // going to nearest vacant building
- Waiting, // waiting for building to be vacant
- Inside, // inside building
- Exiting // finished occupying building and leaving
- };
- public AIState state;
- Transform buildingToGoTo;
- const float WAIT_DISTANCE = 1.0f;
- const float INSIDE_DISTANCE = 0.1f;
- const float WAIT_DURATION = 5;
- const float INSIDE_DURATION = 10;
- void Start()
- {
- SetState(AIState.Going);
- }
- void Update()
- {
- if (state == AIState.Going)
- {
- // go to building
- transform.position = Vector3.MoveTowards(transform.position, buildingToGoTo.position, 0.05f);
- float distanceToBuilding = Vector3.Distance(transform.position, buildingToGoTo.position);
- if (buildingToGoTo.tag == "OccupiedBuilding" && distanceToBuilding <= WAIT_DISTANCE)
- {
- // someone got there ahead of us
- SetState(AIState.Waiting);
- }
- // check if inside already
- else if (buildingToGoTo.tag == "VacantBuilding" && distanceToBuilding <= INSIDE_DISTANCE)
- {
- // mark it as occupied so others won't go here
- buildingToGoTo.tag = "OccupiedBuilding";
- SetState(AIState.Inside);
- }
- }
- else if (state == AIState.Exiting)
- {
- // add code to move to left side
- Destroy(gameObject);
- }
- }
- void SetState(AIState s)
- {
- if (s == AIState.Going)
- {
- buildingToGoTo = FindClosestBuilding().transform;
- }
- else if (s == AIState.Inside)
- {
- // call FinishedInside() after 10 secs
- Invoke("FinishedInside", INSIDE_DURATION);
- }
- else if (s == AIState.Waiting)
- {
- // call FinishedWaiting() after 5 secs
- Invoke("FinishedWaiting", WAIT_DURATION);
- }
- state = s;
- }
- void FinishedInside()
- {
- buildingToGoTo.tag = "VacantBuilding";
- SetState(AIState.Exiting);
- }
- void FinishedWaiting()
- {
- SetState(AIState.Going);
- }
- GameObject FindClosestBuilding()
- {
- GameObject[] gos;
- gos = GameObject.FindGameObjectsWithTag("VacantBuilding");
- GameObject closest = null;
- float distance = Mathf.Infinity;
- Vector3 position = transform.position;
- foreach (GameObject go in gos)
- {
- Vector3 diff = go.transform.position - position;
- float curDistance = diff.sqrMagnitude;
- if (curDistance < distance)
- {
- closest = go;
- distance = curDistance;
- }
- }
- return closest;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement