We create an application that uses hit detection.
This article is part of a series starting with Unity ARKit By Example: Part 1.
In this example we will use another API from Unity-ARKit-Plugin; we will use its ability to detect hits against objects in the physical world from rays projected out from the center of the camera viewfinder.
In particular, when one presses the Place button, the application will place a 30 cm cube if and where a hit is detected.
We start by saving the Hello World scene as Place Cube in the Scenes folder and then:
- We remove the Cube, Canvas, and EventSystem GameObjects
- We add a Button; rename it to PlaceCube
- We update PlaceCube’s Text child GameObject; setting its alignment to center and Text to Place
We next need to create the model (or prefab) to instantiate the GameObjects from.
- We create a Cube GameObject in the scene
- We set its Transform Position to (0,0,0) and Scale to (0.3, 0.3, 0.3)
- We create a folder Assets > Prefabs > Place Cube and drag the Cube into it (this creates a prefab)
- Finally, we delete the Cube from the scene
We create a script; Assets / Scripts / Place Cube / PlaceCube.cs:
- The code is fairly self-explanatory
- In this code, the ARPoint is the center of the camera viewfinder
We add this script as a component on PlaceCube.
We drag the Cube prefab to the Hit Prefab value on the script.
We then attach the HandleClick method to the PlaceCube button:
- On the PlaceCube’s Button component add (plus button) a On Click () entry
- Drag the PlaceCube GameObject onto the entry
- Select the PlaceCube: HandleClick method on the entry
We now follow the instructions in the section The Build Process of the article Unity ARKit By Example: Part 1 to build and load the application to an iOS device. A couple of things to keep in mind:
- We can leave the bundle identifier as we had before
- Make sure to only include the Place Cube scene in the build
Now running the application on an iOS device, we can see the application working.
note: We have to build and load the application to an iOS device to test the application as ARKitRemote does not support hit detection.
In the next article, Unity ARKit By Example: Part 4, we will continue to explore Unity ARKit.