Hi there,
I am making a 2D game for touch devices but I’m having some trouble implementing touch controls. I’ve tried several things such as using Control Freak, coding swipes, etc. but I can’t get it to work.
The kind of controls I am aiming for are similar to those in Mage Gauntlet & Wayward Souls, where the player swipes and holds in a direction, which the character gameObject follows. See - YouTube 00:21 for what I mean.
Can anybody point me in the right direction & help me understand how controls like this work? Any tutorials are welcome! Here is my current script, which is from a tutorial & is not what I’m looking for.
void Update ()
{
float inputModifyFactor = (rigidbody2D.velocity.x != 0.0f && rigidbody2D.velocity.y != 0.0f) ? .7071f : 1.0f;
if (Input.touchCount > 0) {
foreach (Touch touch in Input.touches) {
switch (touch.phase) {
case TouchPhase.Began:
//This is a new touch
isSwipe = true;
fingerStartTime = Time.time;
fingerStartPos = touch.position;
break;
case TouchPhase.Canceled:
//The touch is being canceled
isSwipe = false;
break;
case TouchPhase.Ended:
float gestureTime = Time.time - fingerStartTime;
float gestureDist = (touch.position - fingerStartPos).magnitude;
if (isSwipe && gestureTime < maxSwipeTime && gestureDist > minSwipeDist) {
Vector2 direction = touch.position - fingerStartPos;
Vector2 swipeType = Vector2.zero;
if (Mathf.Abs (direction.x) > Mathf.Abs (direction.y)) {
//Horizontal swipe
swipeType = Vector2.right * Mathf.Sign (direction.x);
} else {
//Vertical swipe
swipeType = Vector2.up * Mathf.Sign (direction.y);
}
if (swipeType.x != 0.0f) {
if (swipeType.x > 0.0f) {
rigidbody2D.velocity = new Vector2 (10, rigidbody2D.velocity.y * inputModifyFactor);
} else {
rigidbody2D.velocity = new Vector2 (-10, rigidbody2D.velocity.y * inputModifyFactor);
}
}
if (swipeType.y != 0.0f) {
if (swipeType.y > 0.0f) {
rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x * inputModifyFactor, 10);
} else {
rigidbody2D.velocity = new Vector2 (rigidbody2D.velocity.x * inputModifyFactor, -10);
}
}
}
break;
}
}
}
}
Thank you so much!