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

Unity开发中如何将鼠标交互逻辑转换为安卓端触摸交互逻辑

Unity安卓端触屏适配鼠标逻辑方案

原有代码使用的是PC端鼠标专属回调OnMouseDown/OnMouseUp,安卓端为触屏交互,直接使用会出现点击无响应问题。以下是可直接替换的适配后代码,同时保留鼠标输入兼容,编辑器下可直接调试:

using System.Collections;
using UnityEngine;

public class ball : MonoBehaviour
{
    public Rigidbody2D rb;
    public float releaseTime = .15f;
    private bool isPressed = false;

    void Update()
    {
        // 安卓触屏输入逻辑
        if (Input.touchCount > 0)
        {
            Touch currentTouch = Input.GetTouch(0);
            Vector2 touchWorldPos = Camera.main.ScreenToWorldPoint(currentTouch.position);
            
            // 触摸按下阶段,检测是否命中当前小球
            if (currentTouch.phase == TouchPhase.Began)
            {
                RaycastHit2D hit = Physics2D.Raycast(touchWorldPos, Vector2.zero);
                if (hit.collider != null && hit.collider.gameObject == gameObject)
                {
                    isPressed = true;
                    rb.isKinematic = true;
                }
            }

            // 触摸拖动阶段,跟随手指位置
            if (isPressed)
            {
                rb.position = touchWorldPos;
            }

            // 触摸抬起/取消阶段,释放小球
            if (isPressed && (currentTouch.phase == TouchPhase.Ended || currentTouch.phase == TouchPhase.Canceled))
            {
                isPressed = false;
                rb.isKinematic = false;
                StartCoroutine(Release());
            }
        }
        // 保留PC/编辑器鼠标输入逻辑,方便调试
        else
        {
            Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            // 鼠标按下检测
            if (Input.GetMouseButtonDown(0))
            {
                RaycastHit2D hit = Physics2D.Raycast(mouseWorldPos, Vector2.zero);
                if (hit.collider != null && hit.collider.gameObject == gameObject)
                {
                    isPressed = true;
                    rb.isKinematic = true;
                }
            }
            // 鼠标拖动跟随
            if (isPressed)
            {
                rb.position = mouseWorldPos;
            }
            // 鼠标抬起释放
            if (isPressed && Input.GetMouseButtonUp(0))
            {
                isPressed = false;
                rb.isKinematic = false;
                StartCoroutine(Release());
            }
        }
    }

    IEnumerator Release()
    {
        yield return new WaitForSeconds(releaseTime);
        GetComponent<SpringJoint2D>().enabled = false;
    }
}
配置注意事项
  • 小球对象必须挂载Collider2D组件(如CircleCollider2D),否则射线命中检测会失效
  • 2D项目请确保相机设置为Orthographic正交模式,透视相机需要额外调整ScreenToWorldPoint的z轴参数
  • Player Settings中Input Handling选项选择Input Manager (Old)或者Both即可正常编译运行
  • 原代码中协程名Realase、时间变量名relaseTime为拼写错误,上述代码已修正为标准的Release/releaseTime

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:06:26