# Rotating object with mouse

I have simple turret on a 2D plane, whose child barrels rotate on its Z axis by 30-150 degrees. At first I had them rotating using J and K keys just for testing and it worked perfectly but I’ve switched it to rotate moving the mouse and I can’t figure out how to rotate it based on just moving the mouse back and forth on the X axis. Here’s my script:

``````using UnityEngine;
using System.Collections;

public class Turret : MonoBehaviour {

//Player Turret
public GameObject barrels;
public float rotateSpeed = 5;

public float minAngle = 60;
public float maxAngle = 280;

void Update () {
//Turret rotation and angle clamp
if(Input.GetAxis("Mouse X") < 0) barrels.transform.Rotate(0, 0, rotateSpeed * Time.deltaTime);
if(Input.GetAxis("Mouse Y") > 0) barrels.transform.Rotate(0, 0, -rotateSpeed * Time.deltaTime);
transform.eulerAngles = new Vector3(0, 0, Mathf.Clamp (transform.eulerAngles.z, minAngle, maxAngle));

}
}
``````

Obviously, moving the mouse on the Y axis isn’t the right way to go, but like I said I can’t figure out how to get the barrels to rotate fully moving the mouse just on the X-axis. Thanks in advance

Here is your problem.

The x/y axis of the mouse are diffrent from the x/y axis of the scene/gameobject.

The 0,0 of the mouse, is the bottom left corner of the screen.

so doing (Input.GetAxis(“Mouse X”) < 0) wont work (at least it’s not supposed to).

You should get the center of the screen by doing Screen.width/2.

Then, you can do x<… x>…

So something like:

``````    int middleScreen = Screen.width/2;
if(Input.GetAxis("Mouse X") < middleScreen) {
// do something
}
if(Input.GetAxis("Mouse X") > middleScreen) {
// do something
}
``````

I hope this is what you meant

Well, I went back to my original script and it seems the solution was there all a long:

``````    if(Input.GetAxis("Mouse X") < 0) {
barrels.transform.Rotate(0, 0, rotateSpeed * Time.deltaTime);
}
if(Input.GetAxis("Mouse X") > 0) {
barrels.transform.Rotate(0, 0, -rotateSpeed * Time.deltaTime);
}

transform.eulerAngles = new Vector3(0, 0, Mathf.Clamp (transform.eulerAngles.z, minAngle, maxAngle));
``````

But I’m not really sure how it’s working even though the middle of the screen is never defined in the script. At any rate, thank you for all the suggestions! I’ve learned quite a bit just trying to figure out something so simple!