Skip to content

Creating a 2D texture trackable at runtime from a downloaded image

Philip Lamb edited this page Apr 28, 2023 · 5 revisions

The "2D" tracker allows runtime creation of 2D texured trackables without any pre-processing of the image ahead-of-time. This represents a significant advantage compared to the original NFT (natural feature tracker) trackables from earlier ARToolKit versions.

In arunityX, creation of a 2D trackable at runtime is achieved by placing the desired image into the filesystem on the device, and then passing the path to the image and the real-world image width (in Unity units, usually metres) to a factory method ARTrackable.Add2D.

string myImageURL = "https://github.com/artoolkitx/arunityx/raw/master/Documentation/Marker%20images/pinball.jpg";
float myImageWidth = 0.188f; // 188 mm wide.
string myImageTrackableTag = "pinball";

StartCoroutine(DownloadAndAdd2D(myImageURL, myImageWidth, (t) => {
    t.Tag = myImageTrackableTag;
    // Do other things with the trackable.
});

IEnumerator DownloadAndAdd2D(string url, float width, string trackableTag, Action<ARTrackable> onSuccess)
{
    string downloadPath = Path.Combine(Application.temporaryCachePath, Path.GetRandomFileName);
    using (www = UnityWebRequest.Get(url))
    {
        www.downloadHandler = new DownloadHandlerFile(downloadPath);
        yield return www.SendWebRequest();
        if (www.result == UnityWebRequest.Result.Success)
        {
            // Attaches the ARTrackable component to the same GameObject as the ARController instance.
            ARTrackable t = ARTrackable.Add2D(downloadPath, width);
            onSuccess(t);
        }
    }
}

Once the ARTrackable has been added, a typical use case is to link it to the pose of an object in the scene. In the example below, it is assumed that the scene already contains an AROrigin component attached to the root of our scene, and an ARCamera somewhere in the scene. We then locate the root of our AR scene by finding the AROrigin component, create a new GameObject under it, and add an ARTrackedObject component to the GameObject, and link the pose the pose (the position and orientation) of this GameObject to our ARTrackable by setting the Tag field on the ARTrackedObject to the same value we set on the ARTrackable above:

AROrigin root = FindObjectOfType<AROrigin>();
GameObject go = new GameObject("myTrackedObject");
go.transform.parent = root.transform;
// position and rotation are set by the trackable, but we should set scale.
go.transform.localScale = Vector3.one;
ARTrackedObject to = go.AddComponent<ARTrackedObject>();
to.Tag = myImageTrackableTag;
Clone this wiki locally