LookAt only on local Z Axis
Hi folks... I want to rotate an object to look in direction of another object while keeping its X and Y angles. (It will rotate on a plane). There are some options avaible on forums but not applicable to my situation. For example on "this example", object rotates on Z axis but X and Y angles always get stuck at 0. And if I write down original X and Y angle instead of 0, it doesn't look at target object anymore. Rotation goes wierd.
In another example, marked answer won't work for me. Because in "a" and "b" vectors, x and y angles are the same. So in direction it will always be 0 and "transform rotation" will only return (0,0,0) or (0,0,180). Correct me if I have done something wrong with this example.
Any help is appreciated...
EDIT:
My code is here:
GameObject rotatingObj;
GameObject targetObj;
private void Update()
{
Vector3 orj_angle = rotatingObj.transform.rotation.eulerAngles;
Vector3 objUp = rotatingObj.transform.forward;
rotatingObj.transform.LookAt(targetObj.transform, objUp );
Vector3 after_rot = rotatingObj.transform.rotation.eulerAngles;
rotatingObj.transform.rotation = Quaternion.Euler(new Vector3(orj_angle.x, orj_angle.y, after_rot.z));
}
private void Start()
{
rotatingObj = GameObject.Find("Quad");
targetObj = GameObject.Find("Cube");
}
Just note what the numbers were before the change and whack them back in before the end of the frame...or zero them or whatever. Are you subject to Gimbal Lock?
I am not sure if it is Gimbal Lock. Rotation goes wild when moving target object. I will add an example file.
It is probably Gimbal Lock, because it follows logically for most of time but after a while it goes haywire. How to overcome this?
Try this, rotation only on z, X and Y angles can be changed independently:
public Transform targetObj;
public Transform rotatingObj;
void Update () {
Vector3 difference = targetObj.position - transform.position;
float rotationZ = $$anonymous$$athf.Atan2(difference.y, difference.x) * $$anonymous$$athf.Rad2Deg;
Vector3 orj_angle = rotatingObj.rotation.eulerAngles;
transform.rotation = Quaternion.Euler(orj_angle.x, orj_angle.y, rotationZ);
}