• 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
6
Question by MrRightclick · Dec 18, 2013 at 11:38 AM · 2drotationspriterotate object

Rotating a Sprite to face mouse / target?

EDIT: For anyone visiting this question: this was typed before Unity had any 2D tools so this might not be suitable for your 2D projects, or it might be an overly complicated way of dealing with the problem. Munchy2007's answer should work fine in most cases.

I've hit a wall here as I switched my very early 2d topdown shooter prototype from a 3D project to a 2D one, and started working with 2D sprites instead of planes with images.

I thought this would be a simple switch, but I'm having some problems getting the sprites to rotate properly. After searching and trying multiple solutions, I still get no results.

My game has Raycast Mouse look:

         // Raycast Mouse Looking
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit = new RaycastHit();
         if (Physics.Raycast (ray, out hit, 100)) {
             Vector3 hitPoint = hit.point;
 
             Vector3 targetDir = hitPoint - transform.position;
 
             targetDir = new Vector3(targetDir.y, targetDir.x, 0); //I tried multiple different setups here, like (0, 0, targetDir.z) etc...
 
             transform.LookAt(targetDir);

As you might see here, I'm trying to use LookAt() function to make the player Sprite rotate towards the Mouse position. This worked fine with 3D planes, but things got awry when I switched to the 2D settings and 2D View.

Two problems: Instead of rotating around one axis, the Sprite rotates the whole GAMEOBJECT, making the sprite warp and turn around like it was on a plane (or a 3D object).

On the other hand, if I get the sprite to stay facing towards the screen and turn around, the sprite turns around in a weird manner, and resets the rotation at certain points when moving the mouse around the sprite. It's like the sprite "Flips" without me ordering it to do so.

I want the sprite to rotate around the Z-AXIS, as in the default Unity 2D view Y is vertical and X is horizontal.

Any solutions? I'm guessing I'm making a very simple mistake somewhere...

Thanks!

Comment
Add comment · Show 2
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 MrRightclick · Dec 18, 2013 at 01:28 PM 0
Share

Update: I tried an example I found, which does not involve Raycasting:

         Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
         Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
         lookPos = lookPos - transform.position;
         float angle = $$anonymous$$athf.Atan2(lookPos.y, lookPos.x) * $$anonymous$$athf.Rad2Deg;
         transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

This works like I want it to (one problem is that the sprite is facing the mouse position sideways ins$$anonymous$$d of forward, but I'll just turn the character around in Photoshop).

Thing is my game is an "arena" type of shooter, where the camera clamps to certain areas, which requires the mouse look to be a Raycast one. Otherwise the when near the edges the character will turn facing the wrong way.

avatar image SnapOut · Feb 04, 2014 at 04:14 PM 0
Share

Finally a solution to my sprite rotating problem!

I've just rotated the sprite 90° afterwards so that it faces the right direction.

Big thanks!

2 Replies

· Add your reply
  • Sort: 
avatar image
8
Best Answer

Answer by MrRightclick · Dec 18, 2013 at 02:35 PM

Answering my own question. I combined the two solutions up there, and ended up with this:

         // Raycast Mouse Looking
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit = new RaycastHit();
         if (Physics.Raycast (ray, out hit, 100)) {
             Vector3 hitPoint = hit.point;
 
             Vector3 targetDir = hitPoint - transform.position;
 
             float angle = Mathf.Atan2(targetDir.y, targetDir.x) * Mathf.Rad2Deg;
             transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
         }


And this seems to be working. The sprite is still rotated 90 degrees clockwise, so facing sideways (the image itself has the character facing down). Any way to fix this other than editing the picture? I like drawing my characters facing up & down.. :)

Comment
Add comment · Show 2 · 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 EZproductions · Jul 15, 2017 at 03:55 PM 0
Share

I am so glad I found this you just fixed my game. Thanks!

avatar image Frankloco · Oct 29, 2020 at 12:34 AM 0
Share

You math is a bit incorrect, in order for the sprite to align. Line 9 should be:

 float angle = $$anonymous$$athf.Atan2(targetDir.x, targetDir.y) * -$$anonymous$$athf.Rad2Deg;
avatar image
26

Answer by Munchy2007 · Feb 04, 2014 at 05:05 PM

I use this to make my sprite follow the mouse. The sprite default orientation is pointing upwards.

 void Update () {
         Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
     }
Comment
Add comment · Show 9 · 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 raylinth · May 04, 2014 at 05:45 PM 0
Share

Fantastic and simple.

avatar image alphster · Jul 04, 2015 at 07:54 AM 0
Share

The best answer by far

avatar image Menno89 · Jul 12, 2015 at 07:02 PM 0
Share

Thanks! used it for my project.

avatar image Siber · Sep 19, 2015 at 10:01 PM 0
Share

For some reason when i was using this code in my game it didn't seem to have a consistent rotation speed. Some angles would cause the "front" of my sprite to be slightly off center to the mouse.

With that said, using the Raycast method above, the exact front of my ship i always pointed directly at the mouse.

avatar image Deviamadev Siber · Oct 08, 2020 at 11:19 PM 0
Share

It could be because it is Vector3, I don't really know how to code.

avatar image klisman · Jan 07, 2016 at 03:02 AM 0
Share

Thank you, very useful!

Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

27 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 avatar image avatar image avatar image

Related Questions

Tracking the object in the 2D game 0 Answers

Trying to rotate a 2D sprite 2 Answers

Constant Rotation in 2D 0 Answers

Rotate a 2D sprite towards target sprite? 0 Answers

Rotating Sprite Stretching Object 1 Answer


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