You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Unity玩家移动的KeyCode键盘触发替换为触屏滑动控制

实现方案

第一步:新增滑动方向存储变量

先在类的成员变量位置新增变量,用来暂存检测到的滑动方向,优先用枚举避免拼写错误:

public enum SwipeDir { None, Up, Down, Left, Right }
private SwipeDir currentSwipe = SwipeDir.None;

第二步:修改滑动检测逻辑

把原滑动代码中输出日志的位置,替换为给滑动方向变量赋值:

if (fingerDown == false && Input.GetMouseButtonDown(0))
{
    startPos = Input.mousePosition;
    fingerDown = true;
}
if (fingerDown)
{
    if (Input.mousePosition.y >= startPos.y + pixelDistToDetect)
    {
        fingerDown = false;
        currentSwipe = SwipeDir.Up;
    }
    else if (Input.mousePosition.y <= startPos.y - pixelDistToDetect)
    {
        fingerDown = false;
        currentSwipe = SwipeDir.Down;
    }
    else if (Input.mousePosition.x <= startPos.x - pixelDistToDetect)
    {
        fingerDown = false;
        currentSwipe = SwipeDir.Left;
    }
    else if (Input.mousePosition.x >= startPos.x + pixelDistToDetect)
    {
        fingerDown = false;
        currentSwipe = SwipeDir.Right;
    }
}
if (fingerDown && Input.GetMouseButtonUp(0))
{
    fingerDown = false;
}

第三步:修改移动触发逻辑

把原移动代码里dirs数组的最后一个参数从KeyCode换成对应的滑动方向枚举,再将按键检测替换为滑动方向匹配判断:

var dirs = new[]
{
    (x - 1, y, hwalls, x, y, Vector3.right, 90, SwipeDir.Left),
    (x + 1, y, hwalls, x + 1, y, Vector3.right, 90, SwipeDir.Right),
    (x, y - 1, vwalls, x, y, Vector3.up, 0, SwipeDir.Down),
    (x, y + 1, vwalls, x, y + 1, Vector3.up, 0, SwipeDir.Up),
};

// 仅检测到滑动时执行移动逻辑
if (currentSwipe != SwipeDir.None)
{
    foreach (var (nx, ny, wall, wx, wy, sh, ang, swipeDir) in dirs.OrderBy(d => Random.value))
    {
        if (currentSwipe == swipeDir)
        {
            if (wall[wx, wy])
            {
                Player.position = Vector3.Lerp(Player.position, new Vector3(nx, ny), 0.1f);
            }
            else
            {
                (x, y) = (nx, ny);
            }
            break; // 匹配到对应方向后直接跳出循环,减少不必要的遍历
        }
    }
    // 处理完移动后重置滑动状态,避免重复触发
    currentSwipe = SwipeDir.None;
}

内容的提问来源于stack exchange,提问作者Hamza Obaidat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:06:02