Created
November 19, 2017 22:22
-
-
Save mimetaur/4857b6f67b2c60337396bc5b6f96fe40 to your computer and use it in GitHub Desktop.
Food Search Algorithm
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 FindFood : MonoBehaviour | |
| { | |
| public Vector2 Search() | |
| { | |
| var foods = GameObject.FindGameObjectsWithTag("Food"); | |
| var food = GetClosestFood(foods); | |
| if (food != null) { | |
| return food.transform.position; | |
| } else { | |
| return new Vector2(8, -16); | |
| } | |
| } | |
| private GameObject GetClosestFood(GameObject[] foods) | |
| { | |
| GameObject closest = null; | |
| float distance = Mathf.Infinity; | |
| Vector3 position = transform.position; | |
| foreach (GameObject food in foods) | |
| { | |
| Vector3 diff = food.transform.position - position; | |
| float curDistance = diff.sqrMagnitude; | |
| if (curDistance < distance) | |
| { | |
| closest = food; | |
| distance = curDistance; | |
| } | |
| } | |
| return closest; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment