asdasdasd
asdasdasd

Reputation: 13

Allow swipeing only to upwards unity

My code below works for detecting swipes and adding force to my game object. However, my aim is to let the user swipe only upwards(Can be up left, up right but never to down). I mean only if user swipes up, AddForce method will be called. When user swipes down nothing will happen. Is it possible to do that, if yes how?

    public class SwipeScript : MonoBehaviour
{
    Vector2 startPos, endPos, direction;
    float touchTimeStart, touchTimeFinish, timeInterval;
    [Range(0.05f, 1f)]
    public float throwForse = 0.5f;


    void Update()
    {
        
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
        {
            touchTimeStart = Time.time;
            startPos = Input.GetTouch(0).position;
            
        }
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
        {
            
            touchTimeFinish = Time.time;
            timeInterval = touchTimeFinish - touchTimeStart;
            endPos = Input.GetTouch(0).position;
            direction = startPos - endPos;
            GetComponent<Rigidbody2D>().AddForce(-direction / timeInterval * throwForse);
            
        }
    }
}

Upvotes: 1

Views: 53

Answers (1)

Palo
Palo

Reputation: 1020

Why wouldn't you just clamp the direction to be nonnegative? For instance, before the last line add something like:

This would be for upward and right:

direction = Vector2.Max(direction, Vector2.Zero); 

and this would be for all upward:

direction = new Vector2(direction.x, Math.Max(direction.y, 0)); 

and I suggest you use

direction = endPos - startPos;

instead of the other way as in your original code, as this way it represents that movement vector correctly. Then remove the negative sign in AddForce in front of the direction as well. Thus:

void Update()
{        
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
    {
        touchTimeStart = Time.time;
        startPos = Input.GetTouch(0).position;
        
    }
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
    {            
        touchTimeFinish = Time.time;
        timeInterval = touchTimeFinish - touchTimeStart;
        endPos = Input.GetTouch(0).position;
        Vector2 direction = endPos - startPos;
        direction = new Vector2(direction.x, Math.Max(direction.y, 0)); 
        GetComponent<Rigidbody2D>().AddForce(direction / timeInterval * throwForse);            
    }
}

Upvotes: 1

Related Questions