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

Unity 2D键盘控制代码适配移动端触摸屏滑动操作改造求助

Unity 2D键盘控制转触屏滑动改造方案

核心实现逻辑

  • 单指左右短滑对应原左右方向键的单次横向移动逻辑
  • 单指短按(未达到滑动阈值)对应原Space键的下落逻辑
  • 保留原有键盘逻辑,方便PC端调试

完整修改后代码

Rigidbody2D rb;
public float speed = 5f; // 原代码未声明该变量,可根据实际需求调整数值
Vector2 newPos;
bool canMove = true;

// 新增触屏相关变量
private Vector2 touchStartPos;
public float swipeThreshold = 100f; // 滑动判定阈值,单位为像素,可根据手感调整

private void Start()
{
    rb = GetComponent<Rigidbody2D>();
    newPos = transform.position;
}

private void Update()
{
    if (canMove)
    {
        // 原有键盘控制逻辑,保留用于PC调试
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            newPos.x += 1.4f;
            transform.position = newPos;                
        }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            newPos.x -= 1.4f;
            transform.position = newPos;
        }
    }
    if (Input.GetKeyDown(KeyCode.Space) && canMove)
    {
        rb.AddForce(Vector3.down * speed);
        canMove = false;
    }

    // 新增触屏输入处理逻辑
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began)
        {
            touchStartPos = touch.position;
        }
        if (touch.phase == TouchPhase.Ended && canMove)
        {
            float swipeDeltaX = touch.position.x - touchStartPos.x;
            // 判定为左右滑动
            if (Mathf.Abs(swipeDeltaX) > swipeThreshold)
            {
                if (swipeDeltaX > 0)
                {
                    // 右滑对应原右方向键逻辑
                    newPos.x += 1.4f;
                    transform.position = newPos;
                }
                else
                {
                    // 左滑对应原左方向键逻辑
                    newPos.x -= 1.4f;
                    transform.position = newPos;
                }
            }
            // 判定为点击,对应原Space键逻辑
            else
            {
                rb.AddForce(Vector3.down * speed);
                canMove = false;
            }
        }
    }

    Vector2 clampPos = transform.position;
    clampPos.x = Mathf.Clamp(transform.position.x, -2.1f, 2.1f);
    transform.position = clampPos;
}

参数调整说明

  • swipeThreshold:滑动判定阈值,数值越大越不容易误触,可在100的基础上根据实际测试手感调整
  • 横向移动步长1.4f、x轴限制范围-2.1f~2.1f均保留原代码逻辑,可按需修改

内容的提问来源于stack exchange,提问作者younes alaoui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:18:01