Skip to content

Instantly share code, notes, and snippets.

@mimetaur
Created November 19, 2017 22:22
Show Gist options
  • Select an option

  • Save mimetaur/4857b6f67b2c60337396bc5b6f96fe40 to your computer and use it in GitHub Desktop.

Select an option

Save mimetaur/4857b6f67b2c60337396bc5b6f96fe40 to your computer and use it in GitHub Desktop.
Food Search Algorithm
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