I have been troubleshooting a prefab for several hours and am out of ideas. It concerns a method that I thought I was comfortable with, transform.LookAt(target). I have this prefab:
As you can see, I verified that the registration points for the eyes are at the center of mass; I also verified that they rotate correctly for the X, Y and Z axes. That yellow ball you see is the target object and IS NOT inside the prefab.
I have tried two means to get the eyes to look at the target. The first is this script, and it caused the eyes to dart 90 degrees counter-clockwise about the y axis (which is very wrong). I applied this script to both eyes. Check it out:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAt : MonoBehaviour
{
public Transform target = null;
// Update is called once per frame
void Update()
{
transform.LookAt(target);
}
}
And please, before you think it: Yes, I remembered to set the target object in the editor. You can see the eyes pointing to the side instead of the target:
I found this other script on the Unity documentation that didn't work at first, but then I changed "Rotation" to "LocalRotation", saw that I was close, reversed the "relativePos" vector, and it worked--but only about the y axis:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAt : MonoBehaviour
{
public Transform target = null;
// Update is called once per frame
void Update()
{
Vector3 relativePos = transform.position - target.position;
// the second argument, upwards, defaults to Vector3.up
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up;
transform.localRotation = rotation;
}
}
You can see here that it works in the XY plane at eye level, but take my word for it when I say the eyes cannot look up or down if I move the ball up or down:
How can I fix this so that the eyes always look at the target I need it to? Thank you sincerely for your time.
EDIT: I fixed it by this sloppy additional rotation, but there has to be a better way:
void Update()
{
//transform.LookAt(target);
Vector3 relativePos = target.position - transform.position;
// the second argument, upwards, defaults to Vector3.up
Quaternion rotation = Quaternion.LookRotation(relativePos, new Vector3(0,1,0));
transform.rotation = rotation*Quaternion.Euler(0,90,0);
}