- Home /
How can I make an object always look at the mouse?
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.
Answer by DoctorSauce · Dec 25, 2013 at 10:00 PM
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:
http://answers.unity3d.com/questions/10615/rotate-objectweapon-towards-mouse-cursor-2d.html
Answer by SixGames101 · Mar 03 at 01:50 PM
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
Your answer
Follow this Question
Related Questions
How to make a gun work with camera? 1 Answer
How to rotate gun only on X and Y axis? 1 Answer
Autorotation to tween gameobject 0 Answers
rotate and tilt at the same time 1 Answer
Rotation with multiple objects 1 Answer