# How can i rotate a GameObject to the mouse pointer?

Hi all i’m a joung c# programmer and this is my first question.

So i ask to you how to rotate a GameObject to the mouse pointer.

I see that my code works only in several spaces of the screen: Image.

I have to rotate the cube to the mouse pointer as you can see in the following Image.

Can anyone helps me to fix this?

This is my code:

lati[0] = Input.mousePosition.x - Screen.width / 2;
lati[1] = Input.mousePosition.y - Screen.height / 2;
lati[2] = Mathf.Sqrt(Mathf.Pow(lati[0], 2) + Mathf.Pow(lati[1], 2));

int i;
int j;
float temp;

for (i = (lati.Length - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (lati[j - 1] > lati[j])
{
temp = lati[j - 1];
lati[j - 1] = lati[j];
lati[j] = temp;
}
}
}
transform.rotation = Quaternion.AngleAxis(Mathf.Rad2Deg * (Mathf.Acos((Mathf.Pow(lati[0], 2) + Mathf.Pow(lati[2], 2) - Mathf.Pow(lati[1], 2)) / (2 * lati[0] * lati[2]))), Vector3.up);
`
Yeah i'm italian.
`

Ok guys i find a solution that works perfectly.

My camera is above the cube (this is not a 2D but a 3D). I needed to rotate my cube in y axes, so the face of cube look the mouse pointer (like a space shooter).

For this solution we need the Carnot’s Theorem.

Mathf.Rad2Deg * (Mathf.Acos((Mathf.Pow(lati[0], 2) + Mathf.Pow(lati[2], 2) - Mathf.Pow(lati[1], 2)) / (2 * lati[0] * lati[2])))

This solution works fine for all degrees.

This is the code:

void Update () {
lati[0] = Input.mousePosition.x - Screen.width / 2;
lati[1] = Input.mousePosition.y - Screen.height / 2;
lati[2] = Mathf.Sqrt(Mathf.Pow(lati[0], 2) + Mathf.Pow(lati[1], 2));

if (lati[0] != 0 && lati[1] != 0)
if (lati[1] > 0)
transform.rotation = Quaternion.AngleAxis(Mathf.Rad2Deg * (Mathf.Acos((Mathf.Pow(lati[0], 2) + Mathf.Pow(lati[2], 2) - Mathf.Pow(lati[1], 2)) / (2 * lati[0] * lati[2]))), Vector3.down);       // 0 - 180
else
transform.rotation = Quaternion.AngleAxis(Mathf.Rad2Deg * (Mathf.Acos((Mathf.Pow(lati[0], 2) + Mathf.Pow(lati[2], 2) - Mathf.Pow(lati[1], 2)) / (2 * lati[0] * lati[2]))), Vector3.up);         // 180 - 360
}
`
`