You need to enable JavaScript to run this app. Unity中如何实现游戏对象随触摸持续更新位置而非仅单次生效
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 06:03:02