Rotate an object to point at a specific point issues

Hey guys,

So, Long story short I’ve been working on a project for the unity asset store and i’ve run into a rather major issue that I need help with.

The project is an Infantry fighting vehicle kit with a handful of prefabs and all the code backing needed to create your own IFVs for your game. One of the key aspects of IFV functionality is controlling the turret on the tanks. Currently i’m using this code to aim the turret at a specific point in world space:

void Update ()
    {
        if (target != new Vector3(-1,-1,-1))
        {           
            if (axis == axisEnum.Y)
            {
                var targetDir = Quaternion.LookRotation(target - transform.position);
                transform.eulerAngles = new Vector3(transform.eulerAngles.x, Quaternion.Slerp(transform.rotation, targetDir, speed * Time.deltaTime).eulerAngles.y, transform.eulerAngles.z);
            }
            else if (axis == axisEnum.X)
            {
                var targetDir = Quaternion.LookRotation(target - transform.position);
                transform.eulerAngles = new Vector3(Quaternion.Slerp(transform.rotation, targetDir, speed * Time.deltaTime).eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z);
            }
            else
            {

            }
        }
        else
        {

        }
    }

I know this code is far from perfect especially in the implementation of Slerp. However, at this point in time I’m more interested in getting a functional prototype version ready. This code seems to function at its very core (IE it aims at the target) However there is a rather serious issue where the turret becomes disconnected from the body of the tank (See pictures)

What the tank starts off looking like (click to enlarge)

2522343--174891--Broken Connection.PNG What the tank looks like after a few seconds of driving on rough terrain (click to enlarge)

Now this is very clearly an issue. I’m not sure why this is happening and I was wondering if anyone could shed some light on a solution or perhaps a better way to achieve a turret with two separate components (as long as it does not involve .lookAt() ;)) Thanks so much for the help guys, I hope i’ve provided enough information.

I suspect you need to be looking at local rotation rather than the global rotation of the two components… quite often the pitfall people run into is switching between world space positions/rotations and the local rotations between the two components to end up pointing at the spot.

This “two component turret” thing comes up quite a bit, especially when you need it to function regardless of parent object’s orientation (upside down on a spacevessel etc.)

Yeah for sure its a common issue. I’ve dug through a half dozen forum posts on this very issue. I was just hoping to find a solution in my current code rather than adopt an entire new method.