# Turret + Cannon Mouse movement

Hey guys, this is a problem I’ve been strugling for days now but I can’t seem to find a proper solution that will help me.

I’ve looked on other questions and formus but still I haven’t find exactly what I need.
I need two scripts: one for a turret that can spin around 360 degrees following the Mouse’s X position and to stop when the X positions are the same. And I also need another script to rotate the cannon that’s attached to the turret, but this has to spin only verticaly and between limits so it doesn’t rotate into itself.

I am trying to make like a world of tanks playing style, this is what I’m trying to achieve:

Also I don’t want any rigid bodies, nor do I want to use the Character Controller package in unity because it uses to much resources.

So far I came up with this:

## Gun Script:

``````var goTarget : GameObject;
var maxDegreesPerSecond : float = 60.0;
private var qTo : Quaternion;

function Start () {
qTo = goTarget.transform.localRotation;
}

function Update () {
var v3T = goTarget.transform.position - transform.position;
var v3Aim : Vector3;
v3Aim.x = 0.0;
v3Aim.y = v3T.y;
v3T.y = 0.0;
v3Aim.z = v3T.magnitude;
qTo = Quaternion.LookRotation(v3Aim, Vector3.up);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, qTo, maxDegreesPerSecond * Time.deltaTime);
}
``````

## Turret Script:

``````var goTarget : GameObject;
var maxDegreesPerSecond : float = 30.0;
private var qTo : Quaternion;

function Start () {
qTo = goTarget.transform.localRotation;
}

function Update () {
var v3T = goTarget.transform.position - transform.position;
v3T.y = transform.position.y;
qTo = Quaternion.LookRotation(v3T, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, maxDegreesPerSecond * Time.deltaTime);
``````

## }

But these follow an object in the game instead of the mouse position. I’ve also looked and ScreenToWorldPoint, Transform.Lookat and Raycasts but It just messes up everything even worse.

How do I limit the rotation of the gun in this script ?

``````//public variables
public var targetFollow        : GameObject;             //load the empty game object that the cannon must follow on y axis
public var maxDegreesPerSecond : float = 60.0;           //rotation speed of cannon

//private variables
private var qTo : Quaternion;

//load the followed object current rotation
function Start () {
qTo = targetFollow.transform.localRotation;
}

// y axis movement to follow target
function Update () {

var v3T = targetFollow.transform.position - transform.position;
var v3Aim : Vector3;

v3Aim.x = 0.0;
v3Aim.y = v3T.y;
v3T.y = 0.0;
v3Aim.z = v3T.magnitude;

qTo = Quaternion.LookRotation(v3Aim, Vector3.up);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, qTo, maxDegreesPerSecond * Time.deltaTime);
``````