How to make my AR character go to the point where I touch on the screen?

Hello, I used the ARCore Template and added a character to the scene (which also contains animations). However, when using the App on the phone, I want the character to actually walk to that point when tapping on a detected surface point. Does anyone know how to do that? :slight_smile:

this is the code I have been using

using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
using System.Collections.Generic;

public class ARTouchToMove : MonoBehaviour
{
    // Reference to ARRaycastManager
    private ARRaycastManager arRaycastManager;

    // Reference to the Bird character (set this in the Inspector)
    public GameObject bird;

    // List to hold the hit results
    private List<ARRaycastHit> hits = new List<ARRaycastHit>();

    void Start()
    {
        // Get the ARRaycastManager component from the ARSessionOrigin
        arRaycastManager = GetComponent<ARRaycastManager>();
    }

    void Update()
    {
        // Check if there is at least one touch input on the screen
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);  // Get the first touch

            // Check for touch phase (when the user taps or moves the finger)
            if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
            {
                // Cast a ray from the screen touch position into the AR world
                Ray ray = Camera.main.ScreenPointToRay(touch.position);

                // Perform the raycast to detect surfaces
                if (arRaycastManager.Raycast(ray, hits, TrackableType.PlaneWithinPolygon))
                {
                    // Get the hit position on the detected plane
                    Vector3 hitPosition = hits[0].pose.position;

                    // Move the Bird to the new position
                    bird.transform.position = hitPosition;
                }
            }
        }
    }
}
1 Like

You can use these resources as Examples to learn Raycast in AR:

You need something like this (I use New Input System to track touches):

private static List<ARRaycastHit> hitResults = new();

public void AddObjectOnDetectedPlane(InputAction.CallbackContext context)
{
    Vector2 touchPosition = context.ReadValue<Vector2>();

    if (arRaycastManager.Raycast(touchPosition, hitResults,
        TrackableType.PlaneWithinPolygon))
    {
        // Raycast hits are sorted by distance, so the first one
        // will be the closest hit.
        Pose hitPose = hitResults[0].pose;

        yourObject.transform.position = hitPose.position;
    }
}

I see, I also tried something similar but still doesn’t work. Thanks anyway for trying!

Are you sure there is a plane where you are tapping? We have a plane visualizer you can use in our samples app to help with this.