- Home /
Swipe position problem
My character moving always to the right everytime i swipe and i have no idea why
using UnityEngine; using System.Collections;
public class Swipe : MonoBehaviour {
public float maxTime;
public float minSwipeDist;
float startTime;
float endTime;
float swipeDistance;
float swipeTime;
Vector3 startPos;
Vector3 endPos;
private Rigidbody _rigidBody;
//axel crap
public float speed = 3f;
void Start()
{
_rigidBody = GetComponent<Rigidbody>();
_rigidBody.AddForce(Vector3.right * 200);
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
startTime = Time.time;
startPos = touch.position;
}
else if (touch.phase == TouchPhase.Ended)
{
endTime = Time.time;
endPos = touch.position;
swipeDistance = (endPos - startPos).magnitude;
swipeTime = endTime - startTime;
if (swipeTime < maxTime && swipeDistance > minSwipeDist)
{
swipe();
}
}
}
}
void swipe()
{
Vector2 distance = endPos - startPos;
if (Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
{
Debug.Log("Horizontal Swipe");
_rigidBody.AddForce(Vector3.right * 200);
}
else if (Mathf.Abs(distance.y) < Mathf.Abs(distance.y))
{
Debug.Log("Vertical Swipe");
_rigidBody.AddForce(Vector3.left * 200);
}
transform.position = Vector3.Lerp(transform.position, endPos, speed * Time.deltaTime);
}
}
There are few problems here. 1. Your else if statement is always false y < y ? 2. You should not move transform if you want to use physics. At least you should do it on rigidbody. 3. Your if statements are strange but if thats what you want then probably because your end point is always at right, it moves to right. check out screen coordinates. end pos is always positive ( between 0,0 and screen resolution )
Answer by fatihsezer · Dec 08, 2016 at 05:15 PM
else if (Mathf.Abs(distance.y) < Mathf.Abs(distance.y))
i think there is a problem
Your answer
![](https://koobas.hobune.stream/wayback/20220612102314im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Root Motion android device problem 0 Answers
Application.LoadLevel Strange Problem 2 Answers
big terrain performance && mobile 1 Answer
C++ windows DLL and Android? 1 Answer
Cant run script second time 1 Answer