LoginSignup
2
4

More than 5 years have passed since last update.

Unityでスワイプ操作

Last updated at Posted at 2019-02-25

実装コード

iOSネイティブのスワイプジェスチャと似た挙動の実装です。移動距離が一定以上になると、指を離さなくても、スワイプ判定が走ります。PC/スマホ対応。

main.cs
//判定距離
private var swipeBorder = 40;
//スワイプの方向
enum SWIPE_DIR {
    RIGHT,
    LEFT,
    NONE
}
//左右スワイプの更新と取得
SWIPE_DIR GetSwipe(){
    if(Input.GetKeyDown(KeyCode.Mouse0)){
        touchStartPos = Input.mousePosition;
        isSwipeStart = true;
    }
    if(Input.GetKey(KeyCode.Mouse0) && isSwipeStart){
        var dirX = Input.mousePosition.x - touchStartPos.x;
        var dirY = Input.mousePosition.y - touchStartPos.y;
        if(Mathf.Abs(dirY) < Mathf.Abs(dirX)) {
            if(swipeBorder < dirX){
                    isSwipeStart = false;
                    return SWIPE_DIR.RIGHT;
            } else if (-(swipeBorder) > dirX){
                isSwipeStart = false;
                return SWIPE_DIR.LEFT;
            }
        }
    }
    return SWIPE_DIR.NONE;
}

使用例

main.cs
void Update () {
    var swipeDir = this.GetSwipe();
    if(swipeDir == SWIPE_DIR.RIGHT) {
        this.prev();
    } else if(swipeDir == SWIPE_DIR.LEFT) {
        this.next();
    }
}
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4