Rotate turret with multiple barrels towards a target and fire

The short version:

I need to rotate a child towards a target, the parent should rotate with it.

The long version:

I have a turret with multiple barrels. Think of it as a ball with multiple cylinders sticking out of it. The cylinders are positioned and rotated arbitrarily.

The cylinders should be selected randomly, the parent rotated towards the target so that the child cylinder faces the target and then the cylinder should fire at the target.

Example image:

74091-turret.jpg

I found some helping code here on the forum, but unfortunately that one works only as long as the z axis isn’t involved.

This is the code I’ve come up with so far:

using UnityEngine;
using System.Collections;

public class RotateTowardsTargetAndFire : MonoBehaviour {

    [Tooltip("The target towards which to rotate.")]
    public Transform target;

    [Tooltip("Speed at which to rotate towards target.")]
    public float rotateSpeed = 100;
    
    [Tooltip("The list of directions / barrels which will be used.")]
    public GameObject[] direction;

    // Current direction array index.
    private int currentDirectionIndex;

    void Start()
    {

        if( direction.Length == 0)
        {
            Debug.LogError("Direction mustn't be empty!");
        }

        NextRandomDirectionIndex();

    }

    void Update () {

        RotateAndFire();

    }

    /**
     * Rotate parent towards target, but using the child for the rotation calculation
     * source partially from: http://answers.unity3d.com/questions/715123/rotate-parent-to-aim-child.html
     */
    void RotateAndFire()
    {
        // get current destination
        GameObject child = direction[currentDirectionIndex];

        // rotate parent towards the direction into which the child faces when it looks at target
        Vector3 angles = child.transform.localEulerAngles;
        Quaternion m_parentToChild = Quaternion.Euler(-angles.x, -angles.y, -angles.z);
        Quaternion lookRotation = Quaternion.LookRotation(target.transform.position - transform.position);
        Quaternion finalRotation = lookRotation * m_parentToChild;

        transform.rotation = Quaternion.RotateTowards(transform.rotation, finalRotation, rotateSpeed * Time.deltaTime);

        // angle to check if we are close enough with the rotation
        float angleDiff = Quaternion.Angle(transform.rotation, finalRotation);

        // fire bullet and get next direction
        if(angleDiff < 0.1f)
        {
            // debug ray / fire bullet
            DebugRay();

            NextRandomDirectionIndex();

        }
    }


    /**
     * Get the next random direction.
     * Ensure that it is different to the current one
     */
    private void NextRandomDirectionIndex()
    {

        // get next index
        int nextIndex = Random.Range(0, direction.Length);

        // ensure that the next index is different to the current one
        if ( currentDirectionIndex == nextIndex)
        {
            nextIndex++;
        }

        if( nextIndex >= direction.Length)
        {
            nextIndex = 0;
        }

        currentDirectionIndex = nextIndex;

    }

    private void DebugRay()
    {
        float length = 5;
        float duration = 2;

    GameObject child = direction[currentDirectionIndex];

    Vector3 forward = child.transform.TransformDirection(Vector3.forward) * length;

    Debug.DrawRay(child.transform.position, forward, color, duration);

    }

}

As long as I rotate the cylinders in design mode only in X and Y direction, everything is fine, but if I rotate around Z, the calculations are off and the shots, i. e. the debug rays go into the floor and in the sky instead of at the target.

Does anyone know how to solve that problem, i. e. rotate the parent so that the child faces a target and then fire a bullet in the direction of the target?

Thank you very much for the help!

Try messing around with an empty game object at the parent. The turret base model as a child of that. Another empty game object as the child of the first game object. With the two barrels as the child to that game object. The parent will have a horizontal rotate script for the turret base movement. the barrels game object will have a vertical movement script. the rotation ahould use localrotate.

Here is a example layout.
Game object
Turret base model
Horizontal movement script
Game object
Vertical movement script
Barrel
Barrel

I will add more when later today once i get home, as i have an example on my pc.

Solved it thanks to this and this post. In case someone else needs it, here’s the relevant code:

Quaternion relativeRotation;

...

    private void NextRandomDirectionIndex()
    {
        // get next index
        int nextIndex = Random.Range(0, direction.Length);

        // ensure that the next index is different to the current one
        if (currentDirectionIndex == nextIndex)
        {
            nextIndex++;
        }

        if (nextIndex >= direction.Length)
        {
            nextIndex = 0;
        }

        currentDirectionIndex = nextIndex;

        GameObject child = direction[currentDirectionIndex];

        relativeRotation = Quaternion.Inverse(transform.rotation) * child.transform.rotation;
    }

    void RotateAndFire()
    {


        GameObject child = direction[currentDirectionIndex];

        Vector3 targetDir = target.transform.position - child.transform.position;
        Quaternion lookRotation = Quaternion.LookRotation(targetDir);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, lookRotation * Quaternion.Inverse(relativeRotation), rotateSpeed * Time.deltaTime);

        float angleDiff = Quaternion.Angle(child.transform.rotation, lookRotation);

        // fire bullet and get next direction
        if (angleDiff < 0.1f)
        {

            // debug ray / fire bullet
            DebugRay();

            NextRandomDirectionIndex();

        }

    }