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

Unity 2D安卓游戏中如何实现适配手机的鼠标物体操控?

适配安卓手机触摸操作的Unity 2D旋转控制实现

针对你的安卓2D游戏,我们可以把原自动旋转的逻辑改成适配手机触摸操作的控制方式,通过单指拖动来模拟鼠标控制物体旋转,同时保留你原本的旋转角度限制(-40°到40°)。

修改后的完整代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchRotateController : MonoBehaviour
{
    public float rotateSensitivity = 0.5f; // 触摸旋转灵敏度
    public float maxRotateAngle = 40f;     // 最大旋转角度限制

    private float currentAngle = 0f;

    void Update()
    {
        // 处理安卓触摸输入
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            
            // 检测触摸拖动过程
            if (touch.phase == TouchPhase.Moved)
            {
                // 根据触摸的X轴偏移量计算旋转增量
                float rotateDelta = touch.deltaPosition.x * rotateSensitivity;
                currentAngle -= rotateDelta;
                
                // 限制旋转角度在[-maxRotateAngle, maxRotateAngle]范围内
                currentAngle = Mathf.Clamp(currentAngle, -maxRotateAngle, maxRotateAngle);
                
                // 应用旋转角度到物体
                transform.rotation = Quaternion.Euler(0, 0, currentAngle);
            }
        }
    }
}

代码说明:

  • 触摸输入处理:通过Input.touchCount和Input.GetTouch(0)获取单指触摸事件,只处理单指拖动(TouchPhase.Moved)的情况,适配手机常用操作逻辑。
  • 旋转灵敏度:rotateSensitivity用来调整触摸拖动时的旋转速度,数值越大旋转越灵敏,可根据游戏手感调整。
  • 角度限制:用Mathf.Clamp确保旋转角度不会超出你设定的±40°范围,和原逻辑保持一致。
  • 直接赋值旋转:替换原自动旋转的Rotate方法,改为直接设置rotation,让触摸控制更精准可控。

额外优化建议:

  • 如果需要支持点击复位旋转,可以添加触摸结束(TouchPhase.Ended)时的复位逻辑。
  • 若要适配多触摸场景,可以扩展为双指缩放+旋转的组合操作,但单指拖动已经满足基础鼠标控制需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:39:19