transform.LookAt with custom forward direction

Hi all. I’m trying to implement horizontal rotation of ‘Guns’ which are child GameObjects of composite GameObject (imagine tank or war ship).

I have 2 turrets and 4 ‘casemate’ guns 2 ‘casemate’ guns at each side of the ‘ship’. Of course each of these guns have it’s own forward direction and my code should handle with this. My current code is following:

public abstract class Artillery : ShipPart
{
    public Vector3 ForwardDirection = new Vector3(0, 0, 1);

    public virtual bool TryHorizontalAimTo(Vector3 Target)
    {
        Target.y = transform.position.y;
        transform.LookAt(Target);
        transform.rotation = Quaternion.LookRotation(ForwardDirection, transform.up) * transform.rotation;
        return true;
    }
}

ForwardDirection field used to specify turret or gun ‘Forward’ direction in Unity editor. Turrets have z=1 and z=-1 directions and they rotated flawlessly. However ‘casemate’ guns which real forward directions are x=1 and x=-1 looks inside the hull after the rotation. I have to switch x direction sign to make them look at target correctly.

All GameObjects have the same transform.up, transform.forward and transform.right.

Pivot points in Blender are also similar.

Turret:

Casemate gun:
79273-gun.png

As you can see both pivot points are in the bottom face of the mesh.

So why my code rotates casemate guns inside the hull unless I enter malformed ForwardDirection value? Any help will be really appreciated.

Not sure if this is what you’re looking for (I could have misread the question), but, since the guns’ Z axis is not facing the direction that the guns are facing, it will mess up the direction it looks in. Try putting an empty game object in between the two guns making sure its Z axis is facing the direction that the guns are facing. Then make the guns a child object of the empty game object and rotate that instead.

By doing this, the axes will already be correct so all you have to do is set the target direction to look in.