- Home /
Y Rotation mousecoords and object rotation
Hello,
Im kinda new to unity, but I was getting around fine untill I tried to rotate my character to the mouse. The code I made doesn't seem to do anything :/ The idea is that I take the center of my character and translate it to screen coords. Then I will do some math with the mouse coordinates and the character screen coordinates to get my rotation.
Though.. Nothing happens
Code: (target is the object that needs to be rotated accordingly)
var target : Transform;
function Update () { var target_onscreen : Vector3 = camera.WorldToScreenPoint (target.position); // viewport coordinates range from zero to one var x=Screen.width*target_onscreen.x; var y=Screen.height*target_onscreen.y;
target.transform.rotation.y=Mathf.Atan2 ( Input.mousePosition.y-y, Input.mousePosition.x-x ) * Mathf.Rad2Deg; print (target.transform.rotation); }
Solved! Working code here:
var target : Transform;
function Update () { var target_onscreen : Vector3 = camera.WorldToScreenPoint (target.position); var x; x = target_onscreen.x; var y; y = target_onscreen.y;
target.transform.eulerAngles=Vector3(0,Mathf.Atan2 ( Input.mousePosition.y-y, Input.mousePosition.x-x ) * Mathf.Rad2Deg,0);
}
Answer by Jesse Anders · Nov 24, 2010 at 10:12 PM
Why are you multiplying the screen coordinates by the screen dimensions? Your comment indicates that maybe you're expecting target_onscreen to be in normalized viewport coordinates, but WorldToScreenPoint() returns coordinates in screen space.
Also, Transform.rotation is a quaternion, not a set of Euler angles, so this line of code:
target.transform.rotation.y=Mathf.Atan2 (...) * Mathf.Rad2Deg;
Doesn't do anything meaningful. If you want to set the y rotation angle directly, assign to transform.eulerAngles.y instead.
Wow, I forgot I changed the command, thank you for pointing that out. I would like to thank you for the part about euler as well. I got it to work now. Ill post the script in case someone wants to use it.
Your answer
Follow this Question
Related Questions
Changing the forward rotation for LookAt 2 Answers
Rotation problem: Check is failing/ endlessly spins 1 Answer
Make 3D Player look exactly at mouse with ScreenToWorldPoint? (maths Question) 2 Answers
How to draw a circle around a moving game object 1 Answer
Rotate object based on hit normal + matching camera direction 0 Answers