Child object "LookAt"

Hi, I’ve been pulling my hair for quite a bit with a child rotation / lookat issue which I can’t seem to be able to wrap my head around.

94684-abc.jpg

The setup is a lot like a turret problem; from the attached image, object A (red) is in the world, C and B are children of A. Obviously, rotating A also rotates C and B within. Now, I need C to look at B and B to look at C (on their X axis).

The following code does that beautifully but only if the rotation of A is zero. I add the script to B and set C as the target, and to C with B as target. They look at eachother as intended. But as soon as “A” rotates (I need it to rotate around its Y axis), the rotations of B and C go haywire.

void Update()
{
    Vector3 direction = Target.position - transform.position;
    float angle = Mathf.Atan2(direction.y, direction.z) * Mathf.Rad2Deg;
    angle = 360 - angle;
    
    Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.right);
    transform.rotation = rotation;
 }

I believe the issue resides in the fact that everything the script does is done in world space and that I would need to do some sort of translation on the final rotation value before applying it but I’m not sure how exactly.

Can anyone can shed some light on that problem?

have you considered using transform.lookat