Unity中如何实现游戏对象随触摸持续更新位置而非仅单次生效
问题核心原因
- 你混淆了屏幕像素坐标和Unity 3D世界坐标两个完全不同的坐标系:
touch.position是屏幕像素值(范围通常是0到你手机屏幕分辨率的宽高),而transform.position是3D世界空间下的坐标,直接赋值必然位置错乱。 - 你没有对触摸阶段做判断,当前代码虽然检测到触摸就执行逻辑,但补充触摸阶段判断可以避免不必要的性能消耗,也能兼容更多操作逻辑。
- 你已经通过ARRaycast拿到了平面检测的3D空间坐标
pose,直接使用这个值即可,不需要再用touch.position赋值。
修正后的代码
using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARSubsystems; using UnityEngine.XR.ARFoundation; using UnityEngine.EventSystems; using UnityEngine.UI; public class PlaceContent : MonoBehaviour { public ARRaycastManager raycastManager; public GraphicRaycaster raycaster; public Text m_Text; private void Update() { if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0); m_Text.text = "Touch Position: " + touch.position; // 触摸开始、移动、静止时都更新位置,满足持续跟随的需求 if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { if (!IsClickOverUI(touch)) { List<ARRaycastHit> hitPoints = new List<ARRaycastHit>(); raycastManager.Raycast(touch.position, hitPoints, TrackableType.Planes); if (hitPoints.Count > 0) { Pose pose = hitPoints[0].pose; // 直接使用AR射线检测得到的3D世界坐标赋值 transform.position = pose.position; // 如果需要保留平面的朝向,可以加上下面这句同步旋转 // transform.rotation = pose.rotation; } } } } else { m_Text.text = "..."; } } bool IsClickOverUI(Touch touch) { PointerEventData data = new PointerEventData(EventSystem.current) { position = touch.position }; List<RaycastResult> results = new List<RaycastResult>(); raycaster.Raycast(data, results); return results.Count > 0; } }
额外优化建议
- 如果不需要每次都新建List,可以把
hitPoints和UI检测的results改成类成员变量,避免频繁GC造成卡顿。 - 如果需要触摸抬起后物体停止跟随,只需要删除判断条件里的
touch.phase == TouchPhase.Stationary即可。
内容的提问来源于stack exchange,提问作者Remy Konings
相关产品推荐
相关产品推荐

