The swipe input
Swiping is probably the second most popular input after tapping. Since I want to be creating more casual mobile games in the future, learning the following piece of code has been very valuable to me:
if(Input.touches.Length > 0){
Touch t = Input.GetTouch(0);
if(t.phase == TouchPhase.Began){
//save began touch 2d point
firstPressPos = new Vector2(t.position.x,t.position.y);
}
if(t.phase == TouchPhase.Moved){ //use .Ended for slower response time
//save ended touch 2d point
secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
//create vector from the two points
currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
//normalize the 2d vector
currentSwipe.Normalize();
//swipe left
if(currentSwipe.x < 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f){
rightSwipe = false;
leftSwipe = true;
}
//swipe right
if(currentSwipe.x > 0 && currentSwipe.y > -0.5f && currentSwipe.y < 0.5f){
leftSwipe = false;
rightSwipe = true;
if (!audio.playOnAwake){
audio.Play();
}
}
}
}
Adding sounds
Besides swiping, I've also learnt how to add sounds to the game. All that's needed to be done, is select the prefab which will activate the sound through code, add the Audio Source component to it, select the sound we want to be using, and deselect the play on awake variable (unless we want to hear the sound when the game starts).

Then we just need to add the following code to a line when we want the sound to trigger:
if (!audio.playOnAwake){audio.Play();
}
I placed it inside the swipe code (tap code after performing the iteration) and it works fine.
Swipe code source:
Swipe in all directions Touch and Mouse [ONLINE] Available at: http://forum.unity3d.com/threads/swipe-in-all-directions-touch-and-mouse.165416/ [Accessed 8th February 2015]
No comments:
Post a Comment