Rotate Z axis of object to camera

Hello guys, I’m having trouble making all connections (3 cylinders with ball) is facing the camera. The core (central sphere) rotates according to the mouse, and when this happens connections must rotate along with the nucleus always turning the cylinders at the camera.

What happens:

What I need:

Code used in connections:

var angle;
 
function Start() {
}
 
function Update  () {
 
    var center : GameObject = GameObject.Find("centro");
 
    var dx = transform.position.x - Camera.main.transform.position.x;
    var dy = transform.position.y - Camera.main.transform.position.y;
    var radians = Mathf.Atan2(dy,dx);
 
    if(center.transform.rotation.eulerAngles.x >= center.transform.rotation.eulerAngles.z)
    {
    angle = radians * 180 / Mathf.PI - (center.transform.rotation.eulerAngles.x/2*-1);
    }
    else
    {
    angle = radians * 180 / Mathf.PI + (center.transform.rotation.eulerAngles.z/2);
    }
 
    var rotateZ = Mathf.LerpAngle(transform.rotation.z, angle, 0);
 
    transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x,transform.rotation.eulerAngles.y,rotateZ),1);
 
}

For 50% of angles this code works. In other cases the object is in the wrong rotation.

public Vector3 axis;

void Update() {
// Do your mouse rotating here

 transform.rotation = Quaternion.FromToRotation(transform.rotation * axis, Camera.main.transform.position - transform.position) * transform.rotation;
}

Attach this to the core GameObject and set “axis” to the local axis that you want to face the camera. What it does basically, it just keeps that axis of the core facing the camera at all times, while maintaining freedom to rotate it around the axis.

Cheers,
Pärtel

If you can build your cylinders within a parent object such that the cylinders point along the object’s Z axis and are separated from each other in the X axis, thus equal in the Y axis, then you just need to orient the parent object with its Z axis along the bond and its Y axis pointing at the camera, which is easy with Quaternion.LookRotation. It’s probably easier to make this change and lean on Unity’s existing function, than it is to write your own function to do the calculation.