# [JS]Rotate object y axis to mouse position

Hello everybody,

after all this years I’m trying to work with unity.
My javascript is good but unity’s javascript is a bit different.
However I have a math problem. Normally I would calculate with math.deg but this function isn’t present. So I did it this way. So I’ve created a testing-cube. It’s rotating like hell but not with the mouse…

However maybe you know a solution. And no, I won’t use any standart assets.
I want to learn and make experience.

``````#pragma strict

function Start(){
}

function Update(){
var cursor = Camera.main.ScreenToWorldPoint( new Vector3( Input.mousePosition.x, Input.mousePosition.z, 10 ) );
var rotation = Mathf.Rad2Deg * Mathf.Atan2( cursor.x - transform.position.x, cursor.z - transform.position.z );
transform.Rotate( 0, rotation, 0 );
Debug.Log( "x: " + cursor.x + ", z: " + cursor.z + ", rotation: " + rotation );
}
``````

So console says mouse position x and z are correct and in 3d. Only the rotation thing doesn’t work…

Greetings,

Bambenek

You are using Rotate incorrectly. Every time transform.Rotate(x) is called, the cube is rotated x amount from its original rotation. The rotation appears random because the rotation is continuously increasing at a fast rate. Try something like the following

`````` function Update(){
var cursor = Camera.main.ScreenToWorldPoint( new Vector3( Input.mousePosition.x, Input.mousePosition.z, 10 ) );
var rotation = Mathf.Rad2Deg * Mathf.Atan2( cursor.x - transform.position.x, cursor.z - transform.position.z );
transform.Rotate( 0, rotation-transform.rotation.y, 0 );
Debug.Log( "x: " + cursor.x + ", z: " + cursor.z + ", rotation: " + rotation );
}
``````