Unity安卓FPS视角输入:OnPointerDown/Up失效及override报错求助
问题解决:Unity安卓FPS视角输入代码修复
一、override关键字报错修复
报错原因:IPointerDownHandler和IPointerUpHandler是接口,并非继承自父类的虚方法,实现接口方法时不能加override关键字,直接移除该关键字即可解决报错。
二、视角输入代码失效问题修复
原代码存在多处逻辑缺陷,以下是修复后的完整代码及问题说明:
修复后代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class LookInput : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { public Vector2 lookInput; public float smoothTime = 8f; public float sensitivity = 3f; // 修正拼写错误:sensivity → sensitivity Vector2 lastPosition; int touchIndex = -1; // 直接初始化,无需在Start中重复赋值 void Update() { if (touchIndex != -1 && touchIndex < Input.touches.Length) { Touch touch = Input.touches[touchIndex]; // Update中使用Time.deltaTime而非Time.fixedDeltaTime lastPosition = Vector2.Lerp(lastPosition, touch.position, smoothTime * Time.deltaTime); // 计算触摸偏移量 Vector2 delta = touch.position - lastPosition; // 基于屏幕尺寸做归一化,避免不同分辨率灵敏度差异 lookInput = new Vector2( delta.x / Screen.width * sensitivity, delta.y / Screen.height * sensitivity ); GameInput.lookInput = lookInput; } else { // 触摸结束后重置输入,防止视角漂移 lookInput = Vector2.zero; GameInput.lookInput = lookInput; } } public void OnPointerDown(PointerEventData data) { touchIndex = data.pointerId; // 触摸开始时初始化lastPosition,避免初始偏移过大 if (touchIndex < Input.touches.Length) { lastPosition = Input.touches[touchIndex].position; } } public void OnPointerUp(PointerEventData data) { touchIndex = -1; } }
原代码问题点说明
- 变量拼写错误:
sensivity应为sensitivity,错误命名可能导致灵敏度设置失效。 - 时间步使用错误:
Update方法中误用Time.fixedDeltaTime(该值用于FixedUpdate),应替换为Time.deltaTime。 - 初始位置未初始化:触摸开始时未将
lastPosition设为当前触摸位置,导致第一帧计算出异常大的偏移量。 - 索引越界风险:未判断
touchIndex是否在Input.touches有效范围内,可能触发空引用错误。 - 无分辨率适配:直接除以固定值
10,不同分辨率设备上灵敏度差异极大,需基于屏幕尺寸做归一化处理。 - 未重置输入:触摸松开后未将
lookInput置零,可能导致视角持续漂移。
三、额外注意事项
- 脚本挂载的物体必须添加UI组件(如
Image,可设置为全透明),因为EventSystem仅能检测UI元素的触摸事件;若要检测全屏任意位置触摸,建议直接使用Input.GetTouch而非UI接口。 - 确保场景中存在
EventSystem物体(创建UI时Unity会自动生成,缺失可右键→UI→EventSystem添加)。 - 检查
GameInput类的lookInput是否为静态可访问变量,确保赋值逻辑有效。
内容的提问来源于stack exchange,提问作者Hadi89
相关产品推荐
相关产品推荐

