Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
10
Question by Neo · Jan 25, 2010 at 11:32 PM · mouse

Rotate object/weapon towards mouse cursor 2d.

I wouldn't think this to be difficult, but apparently it is. I've tried multiple functions (LookAt, Rotate, etc.) and cannot figure out the correct order to get my weapons to always point towards mouse cursor. It is a 2d game, side view shooter. Very similar to crash commandos http://www.youtube.com/watch?v=4bO80FvD2Xs . Need objects to rotate around the z axis and when mouse is clicked a fires towards cursor. Any help or links would be appreciated.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

6 Replies

· Add your reply
  • Sort: 
avatar image
26

Answer by Dusk · Jun 14, 2011 at 08:40 PM

Here. This should work.

 var mouse_pos : Vector3;
 var target : Transform; //Assign to the object you want to rotate
 var object_pos : Vector3;
 var angle : float;
 
 function Update ()
 {
     mouse_pos = Input.mousePosition;
     mouse_pos.z = 5.23; //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;
     transform.rotation = Quaternion.Euler(Vector3(0, 0, angle));
 }

Basically, I just get the position of the mouse on screen, compare it to the target object, convert that to degrees, and rotate the object around the z axis.

Comment
Add comment · Show 15 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Mirath · Aug 29, 2012 at 04:00 AM 0
Share

I was facing a similar problem to the OP, this totally solved it. Thanks!

avatar image trothmaster · Nov 09, 2012 at 09:52 PM 0
Share

This works perfect! Here is how I altered this to work in a 2d sprite game looking down the X/Z axis and only rotating the object on the z axis while keeping the x and y still so the sprite is facing the camera always...I could be doing something wrong but its working perfectly. ins$$anonymous$$d of the mouse I am pointing at "fireTarget"...this could easily be switched to mouse if needed.

var angle = $$anonymous$$athf.Atan2((fireTarget.transform.position.z - armCont.transform.position.z), (fireTarget.transform.position.x - armCont.transform.position.x)) * $$anonymous$$athf.Rad2Deg;

arm.transform.localEulerAngles = Vector3(0,0,angle -270);

avatar image HypoXic5665 · Jan 04, 2013 at 06:09 AM 1
Share

I have been trying to get a LookAt()/RotateTowards() to work for something similar to this for hours now, to no avail. A few modifications to the code you posted and and now the rotation of my object is working perfectly! Thanks for the post Dusk!

avatar image KrishnaMV · Feb 19, 2013 at 08:49 AM 0
Share

im doing same operations in C#.....im getting an error...at Quaternion.Euler....wat am i doing wrong....???

avatar image MehYam · Apr 20, 2014 at 04:06 AM 7
Share

Here's a C# version of the Update() function, simplified slightly:

             var mouse = Input.mousePosition;
             var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
             var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
             var angle = $$anonymous$$athf.Atan2(offset.y, offset.x) * $$anonymous$$athf.Rad2Deg;
             transform.rotation = Quaternion.Euler(0, 0, angle);
 
avatar image Simplexws MehYam · Oct 05, 2016 at 08:16 PM 0
Share

Nice example, Thank you a lot :)

Show more comments
avatar image
10

Answer by tknz · Dec 04, 2013 at 12:22 PM

Dusk's answer workd for me. Here is a c# version that might be useful:

     void Update () {
         //rotation
         Vector3 mousePos = Input.mousePosition;
         mousePos.z = 5.23f;
 
         Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
         mousePos.x = mousePos.x - objectPos.x;
         mousePos.y = mousePos.y - objectPos.y;
 
         float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
         transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
     }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CaveManGaming_YT · May 27, 2020 at 10:02 AM 0
Share

For lines 7 and 8 couldn't you do

 mousePos.x -= objectPos.x;
 mousePos.y -= objectPos.y;
 

avatar image
7

Answer by StephanK · Jan 26, 2010 at 09:09 AM

You can do something like this:

Vector3 mousePos = Input.mousePosition; mousePos.z = -(transform.position.x - Camera.mainCamera.transform.position.x);

Vector3 worldPos = Camera.mainCamera.ScreenToWorldPoint(mousePos);

transform.LookAt(worldPos);

Your guns z-axis (transform.forward) will always point in the direction of you mouse pointer on your 2D-Plane.

Explanation: A cameras ScreenToWorldPosition() will transform a point on your screen to a point in the world. As a mousePosition only has to Coordinates (it's moved on a plane...) You have to tell the ScreenToWorldPosition() method "how far into the screen it should look". Or the distance to the plane that you want to project on.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image agentsmith · Aug 31, 2010 at 06:26 AM 0
Share

Thanks this worked for me!

avatar image SouthTuna · Oct 04, 2013 at 04:18 PM 0
Share

4 simple lines of code did the trick. No trigonometry involved, no planes and no raycasting. Great for what it was intended to do. Thanks, I've been looking for this!

avatar image SpacePilot1000 · Apr 13, 2014 at 03:18 AM 0
Share

This solution won't work for a 2D game that is on the X/Y plane (camera looking into the positive Z axis) which is Unity's default for it's new 2D features. The problem is the transform.LookAt() function won't return the desired result. For such a game, Dusk's solution (see below) will work.

avatar image andredewaard · Sep 14, 2014 at 02:54 PM 0
Share

i have this to work with the transform.position.x set to y. Now it follows my mouse left, right, up and down. But it is always facing up to much. How can i achieve that it is still following but it is facing to the right direction?

avatar image davvjs · Apr 30, 2017 at 09:32 PM 0
Share

Its even easier now:

 var point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
 transform.LookAt(new Vector3(point.x, point.y, transform.position.z));
avatar image
2

Answer by Neo · Jan 29, 2010 at 06:20 AM

Thanks for your help, but it did not work :-( The weapon would not rotate at all. Let me post what I have.

function Update () { var mousePos : Vector3 = Input.mousePosition;

mousePos.z = (transform.position.x - Camera.mainCamera.transform.position.x);

var worldPos : Vector3 = Camera.mainCamera.ScreenToWorldPoint(mousePos);

transform.LookAt(worldPos); }

Also copied what you had into C# same thing of course. If anyone has any ideas on how to make it rotate I sure would appreciate it.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Nicolaj Schweitz · Jan 29, 2010 at 01:46 PM 0
Share

It is best practise to reply to an answer in the comments. Please move this to the correct place once you got enough points. Unfortunately new users are not given enough points to comment and we can't do much about it :-(

avatar image Neo · Jan 30, 2010 at 06:18 AM 0
Share

$$anonymous$$y apologies, that was clearly not my intentions. I just wanted to reply back to the guy, but thank you for letting me know how the system works. If I understand you correctly I must wait until I get more points to remove my answer? I tried to edit and delete but it would not let me save. Let me know what I should do and you have any ideas on the mouse rotation :-)

avatar image Cyclops · Mar 29, 2010 at 01:45 AM 0
Share

@Neo one thing you can do, and generally should :) is update your original post with new information, even if is in response to an Answer. (and you could also add a comment to let them know). Especially if it something like code - also, you can re-edit it to make the code look like code - highlight it, and select the "1010101" button, it turns the text into a code block. Easier to read.

avatar image Sasmaster · Nov 02, 2010 at 03:07 PM 0
Share

It doesn't work for me either

avatar image Zoraph · Dec 11, 2012 at 09:44 PM 0
Share

I had the same problem and that partially (90%) solved it. The mechanic works but it isn't firing in a straight shot, there is a curve in the movement of my bullets when I fire them towards the mouse. The rest seems to be fine.

avatar image
0

Answer by tadadosi · May 27, 2020 at 12:50 PM

I'm using this one in my games, it should work without issues. Apart from having the lookAt2D function, it offers a simple dropdown to choose between X and Y axis and also a bool to easily invert the direction.


alt text


Code:

 using UnityEngine;
 
 public class LookAt2D_v2 : MonoBehaviour
 {
     public Camera cam;
     public enum Axis { x, y }
     public Axis axis = Axis.y;
     public bool inverted;
 
     private Vector3 mousePosition;
     private Vector3 lookAtPosition;
 
     private void Update()
     {
         if (cam == null)
         {
             Debug.LogError(gameObject.name + " target missing!");
             return;
         }
         // store mouse pixel coordinates
         mousePosition = Input.mousePosition;
 
         // distance in z between this object and the camera
         // so it always align with the object
         mousePosition.z = -cam.transform.position.z + transform.position.z;
 
         // transform mousePosition from screen pixels to world position
         lookAtPosition = cam.ScreenToWorldPoint(mousePosition);
 
         // Calculate normalized direction
         Vector2 direction = (lookAtPosition - transform.position).normalized;
 
         Debug.DrawRay(transform.position, direction * 20f, Color.blue);
 
         switch (axis)
         {
             case Axis.x:
                 if (!inverted)
                     transform.right = direction; // Point x axis towards direction
                 else
                     transform.right = -direction; // Point x axis towards inverted direction
                 break;
 
             case Axis.y:
                 if (!inverted)
                     transform.up = direction; // Point y axis towards direction
                 else
                     transform.up = -direction; // Point y axis towards inverted direction
                 break;
 
             default:
                 break;
         }
     }
 
     private void OnDrawGizmos()
     {
         Gizmos.color = Color.yellow;
         Gizmos.DrawWireSphere(lookAtPosition, 0.2f);
     }
 }

look-at-2d-with-simple-dropdown-list-to-choose-bet.png (8.8 kB)
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image safakbahce · Nov 24, 2021 at 09:58 AM 0
Share

Thanks, I will try

  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Right mouse button in webplayer 3 Answers

Making an object clickable 2 Answers

Inside of a ship 1 Answer

external cursor control 1 Answer

Mouse controls sometimes "bounces" 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges