- Home /
[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
Click on the object you are rotating and observe its transform component values when you click Play button.
hey, so I did. Y axis is changine, cube rotation but uncontrolled and not with mouse...
The function you chose performs an instantaneous rotation.
Look up Lerp and look up the use of deltaTime.
now I understand the problem. how should deltaTime solve my problem?
As I think I have to do somethink like:
var mouseX:float = 0;
var mouseY:float = 0;
function Update(){
var mouse = Input.mousePosition;
if ( ( mouse.x - mouseX ) > 5 || ( mouse.y - mouseY ) > 5 ){
Answer by maccabbe · Feb 25, 2015 at 09:34 PM
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 );
}
Your answer
Follow this Question
Related Questions
Rotate object with mouse 1 Answer
Authoritative Rotation 2 Answers
rotation based on mouse position 2 Answers
"Perfect" Free Rotation Method? (like Blender) 2 Answers
Rotate object following mouse movement. Object jumps/ flips 1 Answer