Created
          November 10, 2017 17:46 
        
      - 
      
- 
        Save rdeioris/639f759a8a72f91930f9e9058727b0eb to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| public class ScavengerStateMachine : MonoBehaviour | |
| { | |
| public float Speed; | |
| delegate void ScavengerState(); | |
| ScavengerState currentState; | |
| Mineral bestMineral; | |
| public Transform Home; | |
| // Use this for initialization | |
| void Start() | |
| { | |
| currentState = SearchNearestMineral; | |
| } | |
| // Update is called once per frame | |
| void Update() | |
| { | |
| currentState(); | |
| } | |
| void SearchNearestMineral() | |
| { | |
| bestMineral = null; | |
| Mineral[] minerals = GameObject.FindObjectsOfType<Mineral>(); | |
| float currentDist = float.MaxValue; | |
| for (int i = 0; i < minerals.Length; i++) | |
| { | |
| if (minerals[i].transform.parent != null) | |
| continue; | |
| float distance = (minerals[i].transform.position - this.transform.position).magnitude; | |
| if (distance < currentDist) | |
| { | |
| bestMineral = minerals[i]; | |
| currentDist = distance; | |
| } | |
| } | |
| if (bestMineral != null) | |
| { | |
| currentState = GoToMineral; | |
| } | |
| } | |
| void GoToMineral() | |
| { | |
| Vector3 direction = (bestMineral.transform.position - transform.position).normalized; | |
| direction.y = 0; | |
| if (direction != Vector3.zero) | |
| { | |
| transform.position += direction * Time.deltaTime * Speed; | |
| transform.forward = direction; | |
| } | |
| float distance = (transform.position - bestMineral.transform.position).magnitude; | |
| if (distance < 0.5f) | |
| { | |
| bestMineral.transform.SetParent(transform); | |
| currentState = BringMineralToBase; | |
| } | |
| } | |
| void BringMineralToBase() | |
| { | |
| Vector3 direction = (Home.position - transform.position).normalized; | |
| direction.y = 0; | |
| if (direction != Vector3.zero) | |
| { | |
| transform.position += direction * Speed * Time.deltaTime; | |
| transform.forward = direction; | |
| } | |
| float distance = (transform.position - Home.position).magnitude; | |
| if (distance < 1.5f) | |
| { | |
| bestMineral.transform.SetParent(Home); | |
| currentState = SearchNearestMineral; | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment