タッチ入力による移動方向の指示

タッチ入力について、touch[0]はファーストタッチを指す(2本目のタッチは1になる)
指先でこすった場合、触れ初め(Began)から離したとき(Ended)の移動方向を取得して、
縦と横で大きい方を採用して、上下または左右で1だけ移動する
(斜め移動は無い)

キーボード動作については、斜め入力は横移動を優先する

#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER
  horizontal = (int)(Input.GetAxisRaw("Horizontal"));
  vertical   = (int)(Input.GetAxisRaw("Vertical"));
  if(horizontal!=0) vertical=0;
#else
if(Input.touchCount>0)
{
  Touch myTouch = Input.touch[0];
  if(myTouch.phase==TouchPhase.Began) touchOrigin = myTouch.position;
  else if(myTouch.phase==TouchPhase.Ended && touchOrigin.x>=0)
  {
    Vector2 touchEnd=myTouch.position;
    float x = touchEnd.x - touchOrigin.x;
    float y = touchEnd.y - touchOrigin.y;
    touchOrigin.x=-1;
    if(Mathf.Abs(x)>Mathf.Abs(y))
      horizontal = x>0 ? 1:-1;
    else
      vertical   = y>0 ? 1:-1;
  }
}
#endif
if(horizontal!=0 || vertical!=0 ) Move(horizontal,vertical);


その他

myTouch.deltaPositionで、移動中の指タッチの移動差ベクトルを取れる
myTouch.TapCount

TouchPhase
Began 動き始め
Move 動いてる途中
Ended 動きが終わった
Stationary 動き出す前

タグ:

unity
最終更新:2015年05月30日 16:50