Unity3d 地铁跑酷操控
在 Unity3D 中,地铁跑酷的操控功能是通过代码来实现的。下面将详细介绍具体的地铁跑酷操控代码。
1. 记录操作信息的 Swipe 类
这个类用于记录每次操作的开始点、结束点、开始时间和结束时间。
public class Swipe
{
// 操作结束点
public Vector3 end;
// 操作结束时间
public float endTime;
// 操作开始点
public Vector3 start;
// 操作开始时间
public float startTime;
}
2. 四个滑动方向的枚举 SwipeDir
定义了四个滑动方向(上、下、左、右)以及无滑动的状态。
public enum SwipeDir
{
Up,
Down,
Left,
Right,
None
}
3. 监听 Touch 输入的 HandleControls 方法
该方法用于监听触摸输入,并处理触摸事件以得到输入的 Swipe。
public void HandleControls()
{
// 当游戏未暂停且有触摸输入时
if (!this._paused && (Input.touchCount > 0))
{
// 获取第一个触摸点
Touch touch = Input.touches[0];
// 触摸开始时,初始化 Swipe 对象
if (touch.phase == TouchPhase.Began)
{
this.currentSwipe = new Swipe();
this.currentSwipe.start = (Vector3)touch.position;
this.currentSwipe.startTime = Time.time;
}
// 触摸移动、结束或取消时,处理 Swipe 信息
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;
}
}
// 触摸结束时,若滑动方向为 None,处理点击事件
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. 分析滑动方向的 AnalyzeSwipe 方法
该方法处理并分析得到的 Swipe,通过向量的点乘,得到沿上下左右四个方向上分量最大的那个方向,作为最终结果。
private SwipeDir AnalyzeSwipe(Swipe swipe)
{
// 将开始点从屏幕坐标转换为世界坐标
Vector3 b = Camera.main.ScreenToWorldPoint(new Vector3(swipe.start.x, swipe.start.y, 2f));
// 若滑动距离小于最小距离,返回 None
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 result = SwipeDir.None;
float maxDot = 0f;
// 计算向上方向的点乘
float dotUp = Vector3.Dot(lhs, Vector3.up);
if (dotUp > maxDot)
{
maxDot = dotUp;
result = SwipeDir.Up;
}
// 计算向下方向的点乘
float dotDown = Vector3.Dot(lhs, Vector3.down);
if (dotDown > maxDot)
{
maxDot = dotDown;
result = SwipeDir.Down;
}
// 计算向左方向的点乘
float dotLeft = Vector3.Dot(lhs, Vector3.left);
if (dotLeft > maxDot)
{
maxDot = dotLeft;
result = SwipeDir.Left;
}
// 计算向右方向的点乘
float dotRight = Vector3.Dot(lhs, Vector3.right);
if (dotRight > maxDot)
{
maxDot = dotRight;
result = SwipeDir.Right;
}
return result;
}
通过以上代码,我们可以在 Unity3D 中实现地铁跑酷的基本操控功能,包括滑动和点击操作的处理。