Tuesday, August 21, 2018

unity - Distinguish touch gestures for distinct horizontal and vertical commands


In my script below I'm using horizontal and vertical swipe gesture to move the character but both gestures are called on a single touch.



void Update ()
{
HorizontalSwipe();
VerticalSwipe();
}

void HorizontalSwipe()
{
foreach ( Touch FingerTouchx in Input.touches ) {
if( FingerTouchx.fingerId < 1 ){ // FINGERID

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.phase == TouchPhase.Began)
FingerInitialPositiony = FingerTouchy.position.y;

if(FingerTouchy.phase == TouchPhase.Moved) {
FingerMovedPositiony = FingerTouchy.position.y;

if(FingerMovedPositiony > FingerInitialPositiony)
charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);


if(FingerMovedPositiony < FingerInitialPositiony)
charcter.transform.Translate(-Vector2.down * speed * Time.deltaTime);
}

if(FingerTouchy.phase == TouchPhase.Ended) {
FingerInitialPositiony = 0f;
FingerMovedPositiony = 0f;
}
}
}

}

Whats wrong here? My game character moves in the swipe direction along with continuous jumps.


What I want to achieve is that the character should move horizontally with one touch gesture and vertically(jump) with another touch gesture.


For example: the gesture made on the lower left corner of the touch screen should only consider horizontal movement and make the character move left or right, while the gesture made on the lower right corner should consider only the vertical movement and make the character jump. I'd like to achieve something similar to what's in Leo's Fortune.




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...