HelloAR
HelloAR Example
The easiest sample in which we can get used to ARCore is HelloAR. So we should start by exploring this project. So let's open the sample project.
- In the Unity Project window, navigate to Assets > GoogleARCore > Examples > HelloAR > Scenes > HelloAR.
- Open the HelloAR scene.
- Let's understand the game objects from Hierarchy.
Understanding the Code
Let's select HelloAR Controller game object from Hierarchy. From Inspector, open the HelloARController script. Inside it, there are handle the follwing actions:
- Check for motion tracking
- Detect planes from the real world (on which we will be able to place objects)
- Process user input in order to place objects
- We need to be able to place objects in scene each frame. So the code will be inside the update method.
- When a user taps the screen,
Frame.Raycast()
uses a raycast from the tap position to detect whether the user tapped a plane or other important points from the image (raycasting is a process of checking which objects contain a specific point from the image). - If the user taps a plane or a surface of oriented points, then an ARCore pawn object is instantiated at the
TrackableHit
pose where the user tapped. - The hit pose is used to create an anchor. The anchor keeps the AR game object in the same position relative to the real world. When you no longer need
an anchor, call Unity's GameObject
Destroy()
method on it. This signals ARCore to stop tracking the anchor. - The camera position is used to adjust the ARCore pawn's transform, so that the pawn is in a consistent orientation relative to the camera
- The pawn's transform inherits the hit's anchor so that the pawn game object stays where the user placed it as the user moves their phone around.
// Raycast against the location the player touched to search for planes.
TrackableHit hit;
TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
TrackableHitFlags.FeaturePointWithSurfaceNormal;
if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
{
if ((hit.Trackable is DetectedPlane) &&
Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
hit.Pose.rotation * Vector3.up) < 0)
{
Debug.Log("Hit at the back of the current DetectedPlane");
}
else
{
// Instantiate prefab at the hit pose.
var gameObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
// Compensate for the hitPose rotation facing away from the raycast (i.e.
// camera).
gameObject.transform.Rotate(0, _prefabRotation, 0, Space.self);
// Create an anchor to allow ARCore to track the hitpoint as understanding of
// the physical world evolves.
var anchor = hit.Trackable.CreateAnchor(hit.Pose);
// Make game object a child of the anchor.
gameObject.transform.parent = anchor.transform;
}
}
Last modified: Wednesday, 28 July 2021, 10:39 AM