Hey there. I’m trying to make a code where the gameObject will look at the closest banana. I have the looking part working, but I’m not sure how to get the gameObject to look at bestTarget. This is my first time using returns, so sorry if this is a simple wrong.
using UnityEngine;
using System.Collections;
public class lookAt : MonoBehaviour {
private Vector3 v_diff;
private float atan2;
Transform GetClosestBanana(Transform[] banana)
{
Transform bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = transform.position;
foreach (Transform potentialTarget in banana)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if (dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
void Update () {
GetClosestBanana();
v_diff = (bestTarget.transform.position - transform.position);
atan2 = Mathf.Atan2(v_diff.y, v_diff.x);
transform.rotation = Quaternion.Euler(0f, 0f, atan2 * Mathf.Rad2Deg);
}
}
Thanks