2014年10月17日金曜日

[Unity]Input.Touchesの使い方

https://www.assetstore.unity3d.com/jp/#!/content/3283

・Input.Touchesはスマホのタッチイベントを最適化したスクリプト
・スワイプ、ピンチ、ドラッグ、回転、ダブルタップ、ロングタップ、ショートタップ、チャージなどを検出することができる
・タッチが検出できないPCでの動作ではマウスと同様の動きをする
・価格は25$

使い方
Unity 4.5.5
Input.Touhes v1.1.5

InputTouches > InputPrefb > GestrueのプレハブをHierachyに追加
Hierachyに適当なオブジェクトを追加して新規Scriptを追加
//C# サンプルコード

//オブジェクトが有効になった時に呼び出される
void OnEnable() {
    //onShortTapE、onDoubleTapEというイベントがあるが、
    //onMultiTapEに統合されていおり、
    //onShortTapE、onDoubleTapEはいずれ廃止される 

    //リスナーに登録

    //通常のタップとマルチタップを検出する
    IT_Gesture.onMultiTapE += OnMultiTap;
    //ロングタップ
    IT_Gesture.onLongTapE += OnLongTap;
    //チャージング(タップしたままホールド時間を随時検出)
    IT_Gesture.onChargingE += OnCharging;
    //チャージング終了(チャージ後に指が離れた)
    IT_Gesture.onChargeEndE += OnChargeEnd;
   
    //ドラッグ開始
    IT_Gesture.onDraggingStartE += OnDraggingStart;
    //ドラッグ中
    IT_Gesture.onDraggingE += OnDragging;
    //ドラッグ終了
    IT_Gesture.onDraggingEndE += OnDraggingEnd;
}

//オブジェクトが無効になった時に呼び出される
void OnDisable() {
    //リスナーの登録を解除
    IT_Gesture.onMultiTapE -= OnMultiTap;
    IT_Gesture.onLongTapE -= OnLongTap;
   
    IT_Gesture.onChargingE -= OnCharging;
    IT_Gesture.onChargeEndE -= OnChargeEnd;
   
    IT_Gesture.onDraggingStartE -= OnDraggingStart;
    IT_Gesture.onDraggingE -= OnDragging;
    IT_Gesture.onDraggingEndE -= OnDraggingEnd;
}

//以下のメソッドでタッチを検出する

void OnMultiTap(Tap tap){
    //do a raycast base on the position of the tap
    //対象のオブジェクト(shortTapObj)がタップされているか調べる、
    //1つ1つ調べるのは結構面倒くさい、タップだけならAssetStoreのTouchScriptが良いかも
    Ray ray = Camera.main.ScreenPointToRay(tap.pos);
    RaycastHit hit;
    if(Physics.Raycast(ray, out hit, Mathf.Infinity)){
        //if the tap lands on the shortTapObj, then shows the effect.
        if(hit.collider.transform==shortTapObj){
            //place the indicator at the object position and assign a random color to it
            Indicator.transform.position=shortTapObj.position;
            Indicator.startColor=GetRandomColor();
            //emit a set number of particle
            Indicator.Emit(30);
        }
        //if the tap lands on the doubleTapObj
        else if(hit.collider.transform==doubleTapObj){
            //check to make sure if the tap count matches
            if(tap.count==2){
                //place the indicator at the object position and assign a random color to it
                Indicator.transform.position=doubleTapObj.position;
                Indicator.startColor=GetRandomColor();
                //emit a set number of particle
                Indicator.Emit(30);
            }
        }
    }
}

0 件のコメント:

コメントを投稿