- Home /
Question by
Essexrookie · Jan 04, 2019 at 04:29 AM ·
movementswiperestrict
Restrict diagonal movement when swiping device
Hello there I have a script that moves object in the direction of a swipe but I only need it to go straight up or straight or left to right swipes. I want to restrict diagonal movement when swiping but not sure how to accomplish this
Vector2 startpos, endpos, dir;
float touchstart, touchend, timeint;
public float force;
private Rigidbody2D rb;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchstart = Time.time;
startpos = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
touchend = Time.time;
timeint = touchend - touchstart;
endpos = Input.GetTouch(0).position;
dir = startpos - endpos;
rb.velocity = -dir/timeint * force * Time.deltaTime;
}
}
Comment
Answer by Magso · Jan 05, 2019 at 02:03 AM
Get the swipe speed for X and Y and move the object in which ever is faster.
Vector3 currentPosition = transform.position;
float xSpeed, ySpeed;
void Update()
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
xSpeed = touchDeltaPosition.x;
if(xSpeed < 0){
xSpeed = -xSpeed;
}
ySpeed = touchDeltaPosition.y;
if(ySpeed < 0){
ySpeed = -ySpeed;
}
if(touchDeltaPosition.x > touchDeltaPosition.y){
transform.position.y = currentPosition.y;
}
else if(touchDeltaPosition.x < touchDeltaPosition.y){
transform.position.x = currentPosition.x;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
currentPosition = transform.position;
}
}
This is the only way I can think of.
It's not a complete script, it's just a concept of how to tell which way you're swiping.