This seems like it should be really simple but every script I write seems to not work, so I just figured I should ask. This is a 2D game, unity 4.3. The player is holding a gun and I want to be able to aim the gun with the mouse cursor, so I want the gun to rotate to always be looking at the mouse. Like how you aim guns in Terraria, for those of you who have played it. I have been working on this problem for about a week now! How do I do this? Any help is very, VERY much appreciated.
Alright this is the second time I’ve solved my own problem, I promise I’m not just trying to give myself karma!
For anybody looking for the answer, Dusk’s answer worked perfectly for me on this page:
This is a good solution, but I have a modified implementation
Vector3 mouse_pos; Transform target = null; //Assign to the object you want to rotate Vector3 object_pos; float angle; mouse_pos = Input.mousePosition; mouse_pos.z = 5.23f; //The distance between the camera and object object_pos = Camera.main.WorldToScreenPoint(target.position); mouse_pos.x = mouse_pos.x - object_pos.x; mouse_pos.y = mouse_pos.y - object_pos.y; angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg; target.rotation = Quaternion.Euler(new Vector3(0, -angle + 90, 0));
this works better for 3D or y axis rotation