I'm trying to create a Character touch controls for 2d platform.
In my script Im using one horizontal swipe and hold touch gesture and one vertical swipe gesture without hold.Both are different methods called in void Update ()
.
And here is my script :
void Update ()
{
HorizontalSwipe();
VerticalSwipe ();
}
void HorizontalSwipe()
{
foreach (Touch FingerTouchx in Input.touches)
{
if(FingerTouchx.fingerId<1)// FINGERID
{
//if(FingerTouchx.position.x < Screen.width/2)
if(FingerTouchx.phase == TouchPhase.Began)
{
FingerInitialPositionx=FingerTouchx.position.x;
}
else if(FingerTouchx.phase == TouchPhase.Moved)
{
FingerMovedPositionx=FingerTouchx.position.x;
if(FingerMovedPositionx>FingerInitialPositionx)
{
charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
}
else if(FingerMovedPositionx<FingerInitialPositionx)
{
charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
}
}
else if(FingerTouchx.phase == TouchPhase.Ended)
{
FingerInitialPositionx=0f;
FingerMovedPositionx=0f;
}
else
{
FingerMovedPositionx=FingerTouchx.position.x;
if(FingerMovedPositionx>FingerInitialPositionx)
{
charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
}
else if(FingerMovedPositionx<FingerInitialPositionx)
{
charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
}
}
}
}
}
void VerticalSwipe()
{
foreach (Touch FingerTouchy in Input.touches)
{
if(FingerTouchy.fingerId<1) // FINGERID
{
//if(FingerTouchy.position.y > Screen.width/2)
if(FingerTouchy.phase == TouchPhase.Began)
{
FingerInitialPositiony=FingerTouchy.position.y;
}
if(FingerTouchy.phase == TouchPhase.Moved)
{
FingerMovedPositiony=FingerTouchy.position.y;
}
if(FingerTouchy.phase == TouchPhase.Ended)
{
if(FingerMovedPositiony>FingerInitialPositiony)
{
charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
}
if(FingerMovedPositiony<FingerInitialPositiony)
{
charcter.transform.Translate(-Vector2.up * speed * Time.deltaTime);
}
FingerInitialPositiony=0f;
FingerMovedPositiony=0f;
}
else
{}
}
}
}
Problem:
1:When i swipe and hold horizontally the character moves fine but when i take my finger back it triggers the vertical swipe method.
2:When i try to swipe only vertically the horizontal swipe is also triggered.
3: The two swipe gestures are overlapping and triggered at same time on a Single touch.
Solution(Guess):Dividing the touch screen equally half and forcing horizontal touch gestures strictly on left side of touch screen and vertical touch gestures on right side.
But I'm beginner(You can see my coding style) and would like to know how to do it programatically. Im still learning.