Sample Code Jump straight to the Github repo here
I recently required the functionality of creating a single, persistent local spatial anchor on HoloLens2. The purpose is to provide stability and a persistent real-world location for a hierarchy of 3d model content. In this case there was no need for compatibility with other device types or for persistence across application instances. As a result Azure Spatial Anchors are not really needed and everything can happen locally on a HoloLens2 device without network access. In addition, for my use case only one anchor was needed as the content is relatively small-scale and all bounded within a 3m radius.
We’ll use the Mixed Reality Toolkit Feature Tool to configure the project with the MRTK and the OpenXR Plugin
It is worth noting that since the last time I looked the APIs for this stuff have changed; I recall adding a script WorldAnchor to a gameObject to associate it with a spatial anchor and then using WorldAnchorStore to persist the anchor.
In order to access the correct APIs you would need to add the OpenXR plugin (I used the Mixed Reality Toolkit feature tool to do this).
The newer APIs we will use for this post are:
Also, there is an official sample here upon which this post is based but is slightly simplified here as required for my simpler scenario.
First, I created an AnchorScript.cs and added it to my scene.
The ARAnchorManger and ARSessionOrigin and both in ARFoundation and will get added automatically when adding AnchorScript to a gameObject since they are required components. The AnchorScript itself references 3 items:
- Placing Game Object – this has an ObjectManipulator script attached and will be used to position where we want the local anchor to be in 3d space
- Anchor Prefab – This does not require a graphical element but I used a small coordinate system gizmo so we can identify the root of the anchors coordinate system
- Actual Content – This is a reference to the content that we want to anchor
The transparent cube is used to position a local anchor in space so you can use far interactions or near interactions to position the cube and when the interaction ends a local anchor is created at that position and rotation.
The small axis mesh will show where there is currently a local anchor.
The content under the
ActualContent parent gameObject will be re-parented under the anchored gameObject root. Subsequently introduced content would also be parented unfer that gameObject.
If you close the app and restart the anchor and the content will be positioned relative to where you left it.
The Map Manager part of the HoloLens developer portal provides a view onto the anchor store. You can use this to diagnose creation and deletion of anchors and save/load maps and anchors.