- Home /
Rotate To Object Problems.
void Update () {
var rotation = transform.rotation.z;
Vector3 to = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
Quaternion rot = Quaternion.LookRotation(to - transform.position, Vector3.back);
transform.rotation =rot * new Quaternion(0f, rot.y, 0f, 0f);
}
This is my rotate to object code I have, but the problem is when my mouse cursor is to the right of the player the object will be looking upwards (90 degrees). How can I fix this?
If you have a fix or possible an even better way to rotate to an object ( because this is not indeed pretty at all, X and Y rotations are slightly moving with this code ) I will be glad to learn and listen.
**I'm trying to rotate on the Z axis, This is with the Default 2D Workspace.
Answer by robertbu · Mar 07, 2014 at 04:32 AM
It looks like you are trying to look at the mouse position. There is a solution in this answer:
http://answers.unity3d.com/questions/411548/rotating-to-face-mouse-position-with-two-fixed-axe.html
Note with an Orthographic camera, you can simplify this a bit:
function Update () {
var dir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}