Search Unity

Look at touch direction

Discussion in 'Scripting' started by bugzilla, May 31, 2013.

  1. bugzilla

    bugzilla

    Joined:
    Dec 9, 2008
    Posts:
    196
    I have a spaceship that I instantly want to look in the direction of a swipe event (IOS). I have tried several things but nothing works correctly. Here's the latest code I have. Any ideas?

    Code (csharp):
    1. #pragma strict
    2.  
    3. var startpos:Vector2;
    4. var endpos:Vector2;
    5.  
    6. function Update () {
    7.    for(touch in Input.touches) {
    8.     if(Input.GetTouch(0).phase == TouchPhase.Began){
    9.         startpos = touch.position;
    10.     }
    11.     if(Input.GetTouch(0).phase == TouchPhase.Ended){
    12.         endpos=touch.position;
    13.        
    14.         var angleTouch:float=Vector2.Angle(startpos,endpos);
    15.  
    16.         transform.localEulerAngles.y=angleTouch;
    17.         Debug.Log(angleTouch);
    18.     }  
    19.     //--
    20.    }
    21.  
    22.  //-0-  
    23. }
     
  2. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,697
    Are you sure y is the axis? Other than that, it looks like at touch end, your ship should be rotated on y at that angle to me.
     
  3. Avalion

    Avalion

    Joined:
    May 2, 2012
    Posts:
    34
    Hi !

    First, Vector2.Angle will return an absolute value. if you want to get negative value, use this :
    Code (csharp):
    1. public static float Vector3Angle(Vector3 _from, Vector3 _to) {
    2.     return Vector3.Angle(_from, _to) * ((Vector3.Cross(_from, _to).z < 0) ?  -1 : 1);
    3. }
    Warning, this isn't necessarily z. It can be y.

    I don't really see what you wanted to do with this code...

    If you want to turn view with a finger movement, you'd better check Input.touch[0].deltaposition.

    If you want to turn view with a rotation finger movement, you'd better remember a Vector2 origin is the point (0,0) of the screen. You have to make it relative to the screen Center and so check difference between angles :
    Code (csharp):
    1. float angle = Vector3Angle(Vector2.up, startpos - new Vector2(Screen.width / 2, Screen.height / 2)) - Vector3Angle(Vector2.up, endpos - new Vector2(Screen.width / 2, Screen.height / 2))
    and add it to your localEulerAngles.

    If you want to rotate to what your finger is pointing, you can use Transform.LookAt and Camera.ScreenPointToRay

    Code (csharp):
    1. Transform.lookAt(transform.position + Camera.mainCamera.ScreenPointToRay(Input.touches[0].position).direction);
    Hope this helps

    Avalion
     
    Last edited: May 31, 2013