Unityを用いたスマホゲーム制作で、スワイプの距離だけオブジェクトを移動するというコードを書こうとしているのですが、うまくいきません。
(前提として、transform.positionを直接いじるものではなく、Rigidbodyのvelocityで動かすものとします)
Update()内ではなく、FixedUpdate()内でInputを取得して計算するとInputの取りこぼしがでてしまい、以下のコードではTouchPhase.Ended
を通る前にタッチが終了してまうことがまれに起きてしまいます。
cs
1private Vector2 prePos; 2 3 void FixedUpdate() 4 { 5 if (Input.touchCount == 0) 6 { 7 return; 8 } 9 10 Touch firstTouch = Input.GetTouch(0); 11 12 13 switch (firstTouch.phase) 14 { 15 case TouchPhase.Began: 16 prePos = (Vector2)Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); 17 break; 18 case TouchPhase.Moved: 19 GetComponent<Rigidbody2D>().velocity = ((Vector2)Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) - prePos) / Time.fixedDeltaTime; 20 prePos = (Vector2)Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); 21 22 break; 23 case TouchPhase.Stationary: 24 GetComponent<Rigidbody2D>().velocity = Vector2.zero; 25 Debug.Log("Sationary"); 26 break; 27 case TouchPhase.Ended: 28 GetComponent<Rigidbody2D>().velocity = Vector2.zero; 29 30 Debug.Log("Ended"); 31 break; 32 33 } 34 35 } 36
調べてみるとUniRxのWithLatestFrom
オペレータを用いることで解決できそうなのですが、できればUniRxを使わないで実装したいと考えております。
【UniRx】Update()タイミングのイベントをFixedUpdate()のタイミングに変換する - Qiita
どなたかご教授お願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/02/05 15:35