Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
6
Question by tddaniels · Mar 03, 2014 at 04:13 AM · 2dspriterotate

Make sprite look at vector2 in Unity 2D?

I'm working on a top-down 2D game but can't quite get a sprite to rotate towards any given vector. So far this is the best code I've got for it but the sprite will not look to the left side of the it, only the right:

         transform.LookAt(WorldPos);
         transform.rotation = new Quaternion(0,0,transform.rotation.z, transform.rotation.w);

WorldPos is the point I'm getting from ScreenToWorldPoint. I also have to force the rotation for x and y to 0 so that you can still see the sprite. Anybody got anything better for rotating a sprite toward an object in 2D? I'm thinking it should be this hard.

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

8 Replies

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

Answer by robertbu · Mar 03, 2014 at 04:25 AM

Here something better. I've posted it several times, but as usual searching for the answers is not turning up the ones I want:

 var dir = WorldPos - transform.position;
 var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
 transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

Note this code assumes that the 'forward' side of your sprite is the right side. If it is another side (like up), you will need to adjust the angle (subtract 90) before passing it to the AngleAxis() function;

Comment
Add comment · Show 8 · 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 tddaniels · Mar 04, 2014 at 05:01 AM 0
Share

Yup, works perfectly. I find it ridiculous this was so difficult for me. Thanks a ton.

avatar image cajuuh · Jun 19, 2014 at 03:56 AM 0
Share

thank you i thought with the 4.5 we would have lookAt for 2D already.

avatar image Ronin6 · Jul 28, 2014 at 05:18 PM 0
Share

this problem was killing me for hours. thank you :_)

i had to add 180 to the angle to make it work. i wont pretend i know what all that atan degree math stuff does but thanks

avatar image Kame Sama · Sep 25, 2014 at 04:18 PM 2
Share

Awesome, this works like a charm! I like the flexibility. I'm making a top down 2D game and some sprites I use have different directions. Here's my C# Util function for interested future viewers!

  public enum FacingDirection {
             UP = 270,
             DOWN = 90,
             LEFT = 180,
             RIGHT = 0
         }
 
         public static Quaternion FaceObject(Vector2 startingPosition, Vector2 targetPosition, FacingDirection facing) {
             Vector2 direction = targetPosition - startingPosition;
             float angle = $$anonymous$$athf.Atan2(direction.y, direction.x) * $$anonymous$$athf.Rad2Deg;
             angle -= (float)facing;
             return Quaternion.AngleAxis(angle, Vector3.forward);
         }



avatar image nikocr33nzz Kame Sama · Nov 22, 2016 at 09:25 AM 0
Share

i used your C# code , it worked but it only facing the target not running into the target. how can i do that?

avatar image Ferb nikocr33nzz · Nov 22, 2016 at 01:38 PM 0
Share

You might set the velocity of the Rigidbody2D component to a vector in the direction. If you wanted constant speed, the vector of the velocity would just be the direction normalized, multiplied by the speed.

I'd generally recommend against using the Atan2 function for working out angles on account of it's inefficiency. If you're making a 2D game, quaternions are usually more complicated than we need - I've made a class for handling 2D angles efficiently that has an implicit cast to Quaternion (so you can use it in any function etc. that requires a Quaternion), and if you're finding calculations with angles tricky, you may find it easier to use that. Angles Without Trigonometry (with Angle2D class download at bottom)

avatar image ShaseOfBase Kame Sama · Dec 01, 2016 at 09:58 AM 0
Share

This is gold, thanks broseph!

avatar image RealcakeTheBoss · Apr 02, 2016 at 11:37 AM 0
Share

Amazing, I added this to my script, works like a charm!

avatar image
6

Answer by feyyd · Jul 28, 2014 at 06:43 PM

I have enemy ships in a top down shooting game with very similar behavior. The following is a script that can be attached to a GameObject. It has a public variable for the target your are wanting your object to face, and the update behavior sets the rotation.

 using UnityEngine;
 using System.Collections;
 
 public class FaceTarget : MonoBehaviour
 {
     public Transform target;
     private Vector3 v_diff;
     private float atan2;
 
     void Update()
     {
         v_diff = (target.position - transform.position);    
         atan2 = Mathf.Atan2 ( v_diff.y, v_diff.x );
         transform.rotation = Quaternion.Euler(0f, 0f, atan2 * Mathf.Rad2Deg );
     }
 }

You can programatically add this component and set its target variable as well. If your object is rotated already, you will have to add or subtract an offset from atan2 to compensate for the objects initial rotation.

Comment
Add comment · Show 3 · 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 nirharpaz · May 26, 2015 at 05:35 AM 0
Share

works, but say i want to make this lookAt2D happen over time using Time.DeltaTime, where is this equition do i enter the Time.DeltaTime?

avatar image nirharpaz · May 26, 2015 at 07:25 AM 0
Share

found it

 float trackingSpeed
 
 
 transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0f, 0f, atan2 * $$anonymous$$athf.Rad2Deg ), trackingSpeed*Time.deltaTime);
avatar image MercurialKid · Jan 19, 2020 at 11:56 AM 0
Share

Works well, thanks.

avatar image
2

Answer by IceTrooper · Sep 04, 2018 at 12:02 PM

There is a simpler and cleaner way to do this than in "Best answer":

Vector3 relativeTarget = (target.position - transform.position).normalized;
//Vector3.right if you have a sprite rotated in the right direction
Quaternion toQuaternion = Quaternion.FromToRotation(Vector3.right, relativeTarget);
transform.rotation = Quaternion.Slerp(transform.rotation, toQuaternion, rotationSpeed * Time.deltaTime);

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 RobG88 · Sep 27, 2020 at 08:14 PM 0
Share

Got my vote because of the Slerp implementation.
Had to change Vector3.right to Vector3.up. Works perfectly and as I need. Thanks!

avatar image
1

Answer by Ferb · Oct 22, 2014 at 10:54 PM

There's a dph blog post explaining a few different ways to do the 2D LookAt. I think the simplest way is this:

 transform.LookAt(Vector3.forward,Vector3.Cross(Vector3.forward,direction));

(where 'direction' is a vector pointing in whatever direction you want the sprite to face.)

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 KokodokoGames · Aug 30, 2016 at 03:19 PM 0
Share

This doesn't work for me. The sprite is still rotated along all 3 axes, making it look 3D. I would like the facing to be rotated only along the z axis.

avatar image
0

Answer by Amyth17 · Aug 13, 2014 at 01:17 PM

Try this

using UnityEngine; using System.Collections;

public class JumpScript : MonoBehaviour {

     public int playerSpeed = 5;
 private float rotationx;
 private float rotationy;
 private Vector3 touchcoordinates;
 private Transform myTrans;
 private bool RestartButton_Bool;
 public Transform background_map;
 public Touch touch1;
 public GameObject GameoverText;

 void Start ()
 {
     //Caching of the variables
     myTrans = this.transform;
 }

 // Update is called once per frame
 void Update () 
 {
     //Keep the character without any rotation
     myTrans.rotation = Quaternion.Euler(0,0,0);
     //Check to see if the app is running over iOS or Android Devices
     if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
     {
         //Get touch data
         foreach (Touch touch in Input.touches) 
         {
             touch1 = touch;
             touchcoordinates = touch.position;
             //Coverting touch coordinates in accordance with game use.
             Ray ray = Camera.main.ScreenPointToRay(touchcoordinates); 
             transform.LookAt(ray.GetPoint(-1000),Vector3.forward);

         }
         touchcoordinates = touch1.position;
     }


     //Check if the app is ruuning anywhere other than Mobile devices
     else 
     {
         //Coverting touch coordinates in accordance with game use.
         Ray ray1 = Camera.main.ScreenPointToRay(Input.mousePosition);
         transform.LookAt(ray1.GetPoint(-1000),Vector3.forward);
     }
     //Moving the character forward
     transform.Translate(Vector2.up * Time.deltaTime * 5);
 }

}

Comment
Add comment · 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
  • 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

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

Related Questions

Finding the centre of two touches 2 Answers

Quaternion Rotate Towards Y Value 1 Answer

Sprite "face" second sprite only on Z axis 2 Answers

2D lock x,y rotation to look at target 2 Answers

Mirroring sprite around arbitrary axis causes collision issues 0 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