Autoaiming Turret Cannon?

I’m trying to make a cannon that aim at the player. I can’t seem to make it work properly. So I looked around the web and tried a few scripts but they all make my cannon rotate at odd angles. I’m trying to only make it rotate left-right and up-down (On the Z and X axis).
Here is an image to a similar cannon to the one I made. alt text Also is there a way to specify the pivot point?

http://cgcookie.com/unity/2012/05/22/unity-tower-defense-tutorial-part-01-autoturret/

3 Answers

3

Take a look at this post:

Some changes need to be made if the gun is not at 0 on the Y axis. Plus, when shooting something, the ball is impacted by gravity, so the ball will drop with respect to the target.

It works but it doesn't rotate right because the center of the turret looks at the target not the tip of it.

The easiest way of handling this issue is to use an empty game object. Place the empty game object at the point you want it to pivot. It gets the script. The barrel of the gun is a child of the empty game object, and is translated so that the end of the barrel that pivots is at the empty game object. In addition, I usually put a empty game object just off the other end of the barrel to use as a spawn point for the shells.

if you want it only to rotate on Z and X axis try something like this:

Vector3 cannonOrientationVector;

void Update()
{

cannonOrientationVector = new Vector3(playerObject.transform.position.x, this.transform.position.y, playerObject.transform.position.z);

this.transform.LookAt(enemyOrientationVector);

}

That should work just fine if attached to your cannon script, and if you have the playerObject gameObject available for the cannon script.

Oh, also make sure your cannon starts with a transform.position.y of 0, and cannot be altered anywhere else in the script;

http://forum.unity3d.com/threads/170466-Turret-Aiming

It was just my model was facing the wrong direction.