Unity3d:地鐵跑酷操控解析
1.用於記錄每次操作的開始點和結束點、開始時間和結束時間
public class Swipe
{// Fields
public Vector3 end;
public float endTime;
public Vector3 start;
public float startTime;
}
2.四個滑動方向的列舉
public enum SwipeDir
{
Up,
Down,
Left,
Right,
None
}
3.監聽Touch輸入,得到輸入的Swipe
public void HandleControls()
{
if (!this._paused && (Input.touchCount > 0))
{
Touch touch = Input.touches[0];
if (touch.phase == TouchPhase.Began)
{
this.currentSwipe = new Swipe();
this.currentSwipe.start = (Vector3) touch.position;
this.currentSwipe.startTime = Time.time;
}
if ((((touch.phase == TouchPhase.Moved) || (touch.phase == TouchPhase.Ended)) || (touch.phase == TouchPhase.Canceled)) && (this.currentSwipe != null))
{
this.currentSwipe.endTime = Time.time;
this.currentSwipe.end = (Vector3) touch.position;
SwipeDir swipeDir = this.AnalyzeSwipe(this.currentSwipe);
if (swipeDir != SwipeDir.None)
{
if (this.characterState != null)
{
this.characterState.HandleSwipe(swipeDir);
}
this.currentSwipe = null;
}
}
if ((touch.phase == TouchPhase.Ended) && (this.currentSwipe != null))
{
this.currentSwipe.endTime = Time.time;
this.currentSwipe.end = (Vector3) touch.position;
if ((this.AnalyzeSwipe(this.currentSwipe) == SwipeDir.None) && (this.characterState != null))
{
this.HandleTap();
}
}
}
}
4.處理、分析得到是Swip;通過向量的點乘,得到沿上下左右四個方向上分量做多的那個方向,作為最終結果。
private SwipeDir AnalyzeSwipe(Swipe swipe)
{
Vector3 b = Camera.main.ScreenToWorldPoint(new Vector3(swipe.start.x, swipe.start.y, 2f));
if (Vector3.Distance(Camera.main.ScreenToWorldPoint(new Vector3(swipe.end.x, swipe.end.y, 2f)), b) < this.swipe.distanceMin)
{
return SwipeDir.None;
}
Vector3 lhs = swipe.end - swipe.start;
SwipeDir none = SwipeDir.None;
float num2 = 0f;
float num3 = Vector3.Dot(lhs, Vector3.up);
if (num3 > num2)
{
num2 = num3;
none = SwipeDir.Up;
}
num3 = Vector3.Dot(lhs, Vector3.down);
if (num3 > num2)
{
num2 = num3;
none = SwipeDir.Down;
}
num3 = Vector3.Dot(lhs, Vector3.left);
if (num3 > num2)
{
num2 = num3;
none = SwipeDir.Left;
}
num3 = Vector3.Dot(lhs, Vector3.right);
if (num3 > num2)
{
num2 = num3;
none = SwipeDir.Right;
}
return none;
}
地鐵跑酷的操控手感灰常好,多多學習,多多借鑑。
歡迎大家一起學習討論研究~