Search Unity

Rotate Turret towards touch point

Discussion in 'Scripting' started by unityusing, Jul 23, 2014.

  1. unityusing

    unityusing

    Joined:
    Nov 25, 2013
    Posts:
    11
    in
     
    Last edited: Oct 22, 2015
  2. der_r

    der_r

    Joined:
    Mar 30, 2014
    Posts:
    259
  3. joni-giuro

    joni-giuro

    Joined:
    Nov 21, 2013
    Posts:
    435
  4. der_r

    der_r

    Joined:
    Mar 30, 2014
    Posts:
    259
    I dug up an old prototype I made. Dumping the code. Hope it helps. :)

    The tracking is a loop contained in a co-routine. In the AngleToPlayer function I correct the angle by 90 degrees. This is because there was a miscommunication with my artist and I was too lazy to rotate the sprites. You might not need this.

    I don't know if this is the most elegant way though, it's from my second or third Unity game. :)

    Code (CSharp):
    1.     IEnumerator TrackPlayer()
    2.     {
    3.         isTracking = true;
    4.         float rotateSpeed = 1f;
    5.  
    6.         while(true) {
    7.  
    8.             // Rotate
    9.             float targetHeading = AngleToPlayer();
    10.  
    11.             Quaternion q = Quaternion.AngleAxis(targetHeading, Vector3.forward);
    12.             transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * rotateSpeed);
    13.  
    14.             yield return 0;
    15.         }
    16.     }
    17.  
    18. // -------
    19.  
    20.     float AngleToPlayer()
    21.     {
    22.         Vector3 p2 = GameManager.player.transform.position;
    23.         Vector3 p1 = transform.position;
    24.         return Mathf.Atan2(p2.y-p1.y, p2.x-p1.x)*180 / Mathf.PI - 90;
    25.     }