Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Quaternion.LookRotation in 2D

Discussion in 'Scripting' started by will_brett, Jan 21, 2015.

  1. will_brett

    will_brett

    Joined:
    Feb 16, 2013
    Posts:
    208
    Hey there,

    I made a quick prototype of my game with cubes in 2D where a cube would rotate to face mouse click/ touch. However now that I want to build it in 2d it no longer works as the item to rotates in 3D. How can I fix it so that it only rotates in 2D?

    Here are the code snippets:

    Note: I am using Input.Touches plugin.

    This is how I detect the touch

    Code (CSharp):
    1. void OnMultiTap(Tap tap){
    2.  
    3.         Debug.Log ("Tap");
    4.  
    5.         //do a raycast base on the position of the tap
    6.         //Your custom code;
    7.         Ray ray = Camera.main.ScreenPointToRay (tap.pos);
    8.         RaycastHit hit;
    9.        
    10.         if (tapArea.collider.Raycast (ray, out hit, Mathf.Infinity))
    11.         {
    12.             indicator.position = hit.point;
    13.         }
    14.     }
    and this is how I am rotating the object to face the touch. Which worked in 3d but not 2d

    Code (CSharp):
    1.         Quaternion targetRotation = Quaternion.LookRotation (indicator.transform.position - transform.position);
    2.  
    3.         // Smoothly rotate towards the target point.
    4.         transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, smoothTime * Time.deltaTime);
     
  2. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    Here ya go!

    Code (CSharp):
    1.     protected void LookAt(Vector2 point){
    2.  
    3.         float angle = AngleBetweenPoints(transform.position, point);
    4.         var targetRotation = Quaternion.Euler (new Vector3(0f,0f,angle));
    5.         transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, time.deltaTime);
    6.  
    7.     }
    8.     float AngleBetweenPoints(Vector2 a, Vector2 b) {
    9.         return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
    10.     }
     
  3. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
  4. will_brett

    will_brett

    Joined:
    Feb 16, 2013
    Posts:
    208
    Thanks guys. What I did was clamp the z axis and put the objects under an empty gameobject that was rotated 90 degrees. I will try both the above methods to see which I prefer.

    Thanks
     
  5. garamanx

    garamanx

    Joined:
    Apr 3, 2019
    Posts:
    10
    Excellent job BenZed! I used your 7 years old script for labels on a 2D canvas orbit, which "look" at POIs on a rotatable sphere and connect with a line renderer.

    Thanks a lot!

    upload_2022-11-9_13-30-9.png