Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//Author: Yuri Santos<yrds96@protonmail.com>
//Description this is an example of how to controll gameobjects through the touch controlls
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
enum TouchGesture {
Tap,
SwipeLeft,
SwipeRight,
SwipeUp,
SwipeDown,
None
}
public class PlayerController : MonoBehaviour {
private PlayerActions playerActions;
private Vector2 touchStart = Vector2.zero;
private Vector2 swipeDelta = Vector2.zero;
const int deadZone = 10;
// Start is called before the first frame update
void Start()
{
playerActions = gameObject.GetComponent<PlayerActions>();
}
// Update is called once per frame
void Update()
{
if(jumpAction()) playerActions.jump();
if(dashAction()) playerActions.dash();
if(quickFallAction()) playerActions.quickFall();
}
private TouchGesture getTouchGesture() {
if(Input.touchCount > 0){
Touch touch = Input.GetTouch(0);
switch(touch.phase){
case TouchPhase.Began:
touchStart = touch.deltaPosition;
return TouchGesture.None;
case TouchPhase.Ended:
case TouchPhase.Canceled:
if(intoDeadZone(touch.deltaPosition)) return TouchGesture.Tap;
else return getSwipe();
}
}
return TouchGesture.None;
}
private bool intoDeadZone(Vector2 touchPosition){
swipeDelta = touchPosition - touchStart;
if(swipeDelta.magnitude > deadZone)
return false;
return true;
}
private TouchGesture getSwipe(){
float x = swipeDelta.x;
float y = swipeDelta.y;
if(Mathf.Abs(x) > Mathf.Abs(y)) return x < 0 ? TouchGesture.SwipeLeft : TouchGesture.SwipeRight;
else return y < 0 ? TouchGesture.SwipeDown : TouchGesture.SwipeUp;
}
bool jumpAction(){
if(getTouchGesture() == TouchGesture.Tap) return true;
return false;
}
bool dashAction(){
if(getTouchGesture() == TouchGesture.SwipeRight) return true;
return false;
}
bool quickFallAction() {
if(getTouchGesture() == TouchGesture.SwipeDown) return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment