- Home /
Mobile Swipe Gesture to flick object in 3D space
Hi, I am using the following code in order to try and throw gameobjects based on swipe inputs on a touch screen. However, I am not sure how to make it easier to aim. In its current state, it works vaguely as expected, but the throws are seemingly random and I cannot get the aiming right. Basically I need it so that when you swipe on the screen, the object gets a force acted on it in 3D space accordingly (an example may be a game where you would flick a football into a goal)
void Update () {
if (Input.touchCount > 0)
{
Touch touch = Input.touches[0];
switch (touch.phase)
{
case TouchPhase.Began:
startPos = touch.position;
break;
case TouchPhase.Ended:
float swipeDistHorizontal = (new Vector3(touch.position.x, 0, 0) - new Vector3(startPos.x, 0, 0)).magnitude;
float swipeDistHorizontalActual = (new Vector3(touch.position.x, 0, 0).x - new Vector3(startPos.x, 0, 0).x);
float swipeDistVertical = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude;
if (swipeDistHorizontal > 2)
{
float swipeValue = Mathf.Sign(touch.position.x - startPos.x);
if (swipeValue > 0 && !isTouch)//to right swipe
{
isTouch = true;
//StartCoroutine(Right());
Debug.Log("RIGHT");
}
else if (swipeValue < 0 && !isTouch)//to left swipe
{
isTouch = true;
//(Left());
Debug.Log("LEFT");
}
}
//add swipe to up
if(swipeDistVertical > 2)
{
float swipeValue = Mathf.Sign(touch.position.y - startPos.y);
if(swipeValue > 0)
{
isTouch = true;
Debug.Log("UP");
}
}
GameObject cheese = cheesePool.transform.GetChild(Random.Range(0, cheesePool.transform.childCount - 1)).gameObject;
cheese.transform.position = spawnPos;
cheese.AddComponent<Rigidbody>();
cheese.GetComponent<Rigidbody>().AddForce(new Vector3(swipeDistHorizontalActual, 0.45f * swipeDistVertical, swipeDistVertical) * force);
cheese.transform.SetParent(null);
isTouch = false;
break;
// case TouchPhase.Ended:
// //isSwipe = false;
// isTouch = false;
// break;
}
The gameobjects I am throwing are the "cheese" objects which are loaded from a pool.
Any help is greatly appreciated, thanks.
Comment