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
相关产品推荐
相关产品推荐

