Skip to main content

Simple swipe in unity using angle calculation for touch devices

Today i am gonna post on how to do Simple swipe using angle calculation in unity for touch devices.


as you can see in the image every direction have a touch area of 60' so if your swipe falls in that area, than according to your conditions, respective swipe gesture will be called.
To use the below given script, attach it to an empty gameObject and than drag your player to the player variable in the inspector and check the results.




using UnityEngine;
using System.Collections;

public class SwipeSimpleCS : MonoBehaviour {
    
    public Transform player// Drag your player here
    private Vector2 fp// first finger position
    private Vector2 lp// last finger position
    private float angle;
    private float swipeDistanceX;
    private float swipeDistanceY;
    
    void Update () {
        foreach(Touch touch in Input.touches)
        {
            if (touch.phase == TouchPhase.Began)
            {
                fp = touch.position;
                lp = touch.position;
            }
            if (touch.phase == TouchPhase.Moved )
            {
                lp = touch.position;
                swipeDistanceX = Mathf.Abs((lp.x-fp.x));
                swipeDistanceY = Mathf.Abs((lp.y-fp.y));
            }
            if(touch.phase == TouchPhase.Ended)
            {
                angle = Mathf.Atan2((lp.x-fp.x),(lp.y-fp.y))*57.2957795f;
                
                if(angle > 60 && angle < 120 && swipeDistanceX > 40    )
                {
                    print ("right");
                    player.Rotate(0,45,0);
                }
                if(angle > 150 || angle < -150 && swipeDistanceY > 40)
                {
                    print ("down");
                    player.position+=new Vector3(0,-2,0);
                }
                if(angle < -60 && angle > -120 && swipeDistanceX > 40)
                {
                    print ("left");
                    player.Rotate(0,-45,0);
                }
                if(angle > -30 && angle < 30 && swipeDistanceY > 40)
                {
                    print ("up");
                    player.position+=new Vector3(0,2,0);
                }
            }
        }
    }
}






If you like this post and want to contribute Please click on the link given below.


https://www.paypal.me/Sushanta1991

Comments

  1. Replies
    1. Hi Mago.. 57.2957795 is 180/pi

      Here "Mathf.Atan2((lp.x-fp.x),(lp.y-fp.y))" i am getting the value in radian, so i need to multiply it with 180/pi to get a value in degree.
      Hope now you understand why i am multiplying that number.

      Delete
    2. Do you know how I can make this to make an Object move in that specific Angle?

      Delete
    3. Hey Mago, sorry for this late reply, i was too busy.
      Answer to your question is, you just need to assign the angle to your players Y rotation and your player will move in the direction, that you swiped.

      e.g.

      angle = Mathf.Atan2((lp.x-fp.x),(lp.y-fp.y))*57.2957795f;
      player.rotation = Quaternion.Euler(0,angle,0);

      Delete
  2. can you help me please, why jump animation does not work ?

    using UnityEngine;
    using System.Collections;

    public class Swipe : MonoBehaviour {

    public Transform player;
    private Vector2 fp;
    private Vector2 lp;
    private float angle;
    private float swipeDistanceX;
    private float swipeDistanceY;
    private Vector3 moveDirection = Vector3.zero;

    void Update () {
    foreach(Touch touch in Input.touches)
    {
    if (touch.phase == TouchPhase.Began)
    {
    fp = touch.position;
    lp = touch.position;
    }
    if (touch.phase == TouchPhase.Moved )
    {
    lp = touch.position;
    swipeDistanceX = Mathf.Abs((lp.x-fp.x));
    swipeDistanceY = Mathf.Abs((lp.y-fp.y));
    }
    if(touch.phase == TouchPhase.Ended)
    {
    angle = Mathf.Atan2((lp.x-fp.x),(lp.y-fp.y))*57.2957795f;

    if(angle > 60 && angle < 120 && swipeDistanceX > 40 )
    {
    print ("right");
    player.position+=new Vector3(2,0,0);
    }
    if(angle < -60 && angle > -120 && swipeDistanceX > 40)
    {
    print ("left");
    player.position+=new Vector3(-2,0,0);
    }
    if(angle > -30 && angle < 30 && swipeDistanceY > 40)
    {
    animation.Play("jump_pose");
    }
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. Hi Irfani, code looks fine, it should work.
      Please check if you place this script on your player or not ? because you are calling animation.Play("jump_pose");
      so you must have an animation component on your object where you are attaching thing script and also make sure that animation component should have an animation "jump_pose". otherwise it will not work.

      Delete
  3. Thanks for the above angle script!!!

    ReplyDelete

Post a Comment

Popular posts from this blog

How to write data to CSV file in UNITY

Hi Guys, if any one is facing problem to save data in csv file can use this solution. If you have any questions, you can ask me through comments.

Things to remember :
Never ever add any commas to your data otherwise, cells will get messed up completely. 


Results :


Here is the code

usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO;
usingSystem;

publicclassCsvReadWrite : MonoBehaviour {

privateList<string[]> rowData = newList<string[]>();


//Usethisforinitialization
voidStart () {
Save();
    }

voidSave(){

//CreatingFirstrowoftitlesmanually..
string[] rowDataTemp = newstring[3];
rowDataTemp[0] = "Name";
rowDataTemp[1] = "ID";
rowDataTemp[2] = "Income";
rowData.Add(rowDataTemp);

//Youcanaddupthevalues

Simple Up, Down, Left, Right Swipe controls for touch devices( Iphone and Android) in unity

Note: There are more than 50 comments in this post, So, if your comment is not appearing on the first page than' 'don't get panic', there is aLoad Morebutton at the bottom of the page.



Here is a UnityScript (javascript version)

#pragma strict
var player : Transform;  // Drag your player here
privatevar fp : Vector2;  // first finger position
privatevar lp : Vector2;  // last finger position

function Update()
{
for (var touch : Touchin Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fp = touch.position;
lp = touch.position;
}
if (touch.phase == TouchPhase.Moved )
{
lp = touch.position;
}
if(touch.phase == TouchPhase.Ended)
{

if((fp.x - lp.x) > 80) // left swipe
{

player.Rotate(0,-90,0);

}
else if((fp.x - lp.x) < -80) // right swipe
{
player.Rotate(0,90,0);
}
else if((fp.y - lp.y) < -80 ) // up swipe
{
// add your jumping code here
}
}
}


}


add this script to any empty gameObject or your player than drag your player to player variable in editor now build a .apk or .ipa and check the re…

How to create line graph in unity

Hi guys, previously i have shown how you can create Bar_Graph in unity, after successfully showing bar graph in unity i fell in love with graphs, so when i was asked to show data on a line graph, i got excited and came up with this solution, its almost similar to the bar graph, but this time i have made it more reliable and dynamic.

this is how my setup looks like :




I have an orthographic camera in my scene, which only renders a layer i namded "GUI". and every gameobject in the graph are in "GUI" layer.

why orthographic camera ? its because they easily adjust according to different screen resolutions, i have also used textMesh to show the numbers in graph, which again is the best option if you want to show text in 3d space.


here is a view, how the final graph looks like with data :






in the above image you can see that i am showing data for 99 turns,  but in this small space i cant show data for all the 99 turns, so what i did is i made a dynamic function which give…