- Home /
The question is answered, right answer was accepted
How to Find an Object close to where the Player is Looking
I am trying to make it so when this method is called, it will return the closest gameobject to where I am looking. This works great except it doesn't take into account the y axis for some reason.
[SerializeField] private string[] astTags;
public GameObject FindTarget (Transform player)
{
List<GameObject> objs = new List<GameObject>();
foreach (string astTag in astTags) {
foreach (GameObject ast in GameObject.FindGameObjectsWithTag (astTag))
objs.Add (ast);
}
if (objs.Count == 0)
return null;
float[] angle = new float[objs.Count];
int i = 0;
foreach (GameObject obj in objs) {
float multiplier;
if (obj.CompareTag ("Enemy"))
multiplier = 0.5f;
else
multiplier = 1f;
angle[i] = Quaternion.Angle (player.rotation, Quaternion.LookRotation (obj.transform.position - player.position)) * multiplier;
i++;
}
return objs[Array.IndexOf (angle, angle.Min())];
}
Answer by DAMO238 · Oct 26, 2017 at 07:32 PM
I found a fix, using Quaternion.LookRotation (player.forward) instead of player.rotation not 100% sure why that worked but it did.
Follow this Question
Related Questions
How can I pitch and roll a circular platform without releasing vertical/horizontal input? 1 Answer
Quaternion Slerp - Rotate to Angle? 1 Answer
Rotating tank barrel on X axis while the parent Turret rotates on Y axis 2 Answers
A node in a childnode? 1 Answer
How Do I accurately rotate a player 180 degrees about the Z axis? 1 Answer