- Home /
swipe player to up jump.
This is probably extremely simple but bare with me i'm new to touch inputs. I'm creating a game for android devices where when the player swipes up the character jumps. Any insight on how to achieve this?
For that I used one link code:-
void Update() { #if UNITY_ANDROID || UNITY_IPHONE if (Input.touchCount > 0) { Touch touch = Input.touches[0];
switch (touch.phase)
{
case TouchPhase.Began:
startPos = touch.position;
StartCoroutine(Jump());
break;
case TouchPhase.Moved:
isSwipe = true;
float swipeDistHorizontal = (new Vector3(touch.position.x, 0, 0) - new Vector3(startPos.x, 0, 0)).magnitude;
float swipeDistVertical = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude;
if (swipeDistHorizontal > minSwipeDistX)
{
float swipeValue = Mathf.Sign(touch.position.x - startPos.x);
if (swipeValue > 0 && !isTouch)//to right swipe
{
isTouch = true;
StartCoroutine(Right());
}
else if (swipeValue < 0 && !isTouch)//to left swipe
{
isTouch = true;
StartCoroutine(Left());
}
}
//add swipe to up
if(swipeDistVertical > minSwipeDistY)
{
float swipeValue = Mathf.Sign(touch.position.y - startPos.y);
if(swipeValue > 0 && !isTouch)
{
isTouch = true;
StartCoroutine(Jump2());
}
}
break;
case TouchPhase.Ended:
isSwipe = false;
isTouch = false;
break;
}
}
#endif
} IEnumerator Jump2() { yield return new WaitForSeconds(0.05f); if(playerVelocity <= 0.2f) { Debug.Log("Swipe Up"); } }
IEnumerator Jump() { if (!isSwipe) { yield return new WaitForSeconds(0.05f); if (!isSwipe && playerVelocity <= 0.2f) { Debug.Log("Tap");
}
else
{
yield break;
}
}
else
{
yield break;
}
}
IEnumerator Right() { Debug.Log("Right");
}
IEnumerator Left() { Debug.Log("Left");
}
Answer by Batka · Nov 15, 2016 at 11:13 AM
Here is how I did it, but using Character Controller
If you are using real life physics, this is not very useful.
private Vector3 moveDirection = Vector3.zero;
private CharacterController cc;
public float gravity = 9.81f;
void Update() {
if (Input.touches.Length > 0)
{
Touch t = Input.GetTouch(0);
if (t.phase == TouchPhase.Began)
{
//save began touch 2d point
firstPressPos = new Vector2(t.position.x, t.position.y);
}
if (t.phase == TouchPhase.Ended)
{
//save ended touch 2d point
secondPressPos = new Vector2(t.position.x, t.position.y);
//create vector from the two points
currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
//normalize the 2d vector
currentSwipe.Normalize();
//swipe up
if (currentSwipe.y > 0 && currentSwipe.x > -0.5f && currentSwipe.x < 0.5f && _characterController.isGrounded)
{
moveDirection.y = jumpSpeed;
}
//make the character fall each update
moveDirection.y -= gravity * Time.deltaTime;
moveDirection.z = zVelocity;
_characterController.Move(moveDirection * Time.deltaTime);
}
I hope it leads you somewhere safer :P