World Anchor code

Here, we will implement World Anchors. We will go through what we add line by line and learn what everything means. Just to set expectations, this next section is almost entirely code-based.

In our fields and properties area, we need to add the two lines that are at 11 and 12 in the picture below. Depending on how you have your own code written, these numbers may not line up exactly, but should be close; this screenshot shows you the code that surrounds it to give reference points:

In the first of the two lines, we are creating a string to give our anchor a name.

The second line will be used to get a reference to our WorldAnchorManager Singleton, which we will set up next, in our Start() function.

From this screenshot, you need line 40 and then lines 48-55; lines 43-46 should already be there:

The first thing we add, at line 40, is the wAnchorManager reference to the WorldAnchorManager we just talked about.

Lines 48-55 check whether wAnchorManager is not null and that spatialMappingManager is not null. If these two conditions are met, we use our reference to the WorldAnchorManager to attach and anchor to our skee object. We are also assigning the name stored at skeeBallAnchorName.

One common way to reference a gameObject in code, but which can be confusing to new scripters, is as follows:

  • gameObject (notice the lower case g): This is the actual game object you are attached to.
  • this.gameObject: This is the same as gameObject.
  • this: This is a reference to the specific mono behavior attached to the current game object. If you have three components assigned to an object and want to delete one of those three without affecting anything else, this is the one to use.

In the update function, we just have one small change. Here, we add the height buffer that we created in the preceding chapter and apply it to the not parent version of the class, on line 102:

hitInfo is the result of a raycast being sent from the user's head. We are using that result to position the object where the user is looking at. We are replacing the Vector3 hitInfo.point with a new Vector3 that is the same refactored out to an individual axis and adding the height buffer to y.

Now, in our OnInputClicked function, we will be changing two lines--one to attach an anchor and one to remove an anchor; simple enough:

First on, line 119, we will need to add wAnchorManager.RemoveAnchor(gameObject). This translates to tell the AnchorManager Singleton to remove the anchor from the gameobject this script is attached to.

Line 128 is exactly the same as what we used at line 50 with the caveat of being in response to a click, as opposed to the start of the script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.190.101