Skip to content

Instantly share code, notes, and snippets.

@neogeek
Created April 10, 2018 01:48
Show Gist options
  • Save neogeek/dffaa3769ba772ea796a5a6361f2300b to your computer and use it in GitHub Desktop.
Save neogeek/dffaa3769ba772ea796a5a6361f2300b to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.iOS;
public class ARKitObjectController : MonoBehaviour
{
public Camera mainCamera;
public Light mainDirectionalLight;
public Material clearMaterial;
private bool anchorSet = false;
private void Awake()
{
ChildrenSetActive(false);
}
private void Start()
{
if (mainCamera == null)
{
mainCamera = Camera.main;
}
if (mainDirectionalLight == null)
{
mainDirectionalLight = Object.FindObjectOfType<Light>();
}
if (mainCamera.gameObject.GetComponent<UnityARVideo>() == null)
{
UnityARVideo unityARVideo = mainCamera.gameObject.AddComponent<UnityARVideo>();
unityARVideo.m_ClearMaterial = clearMaterial;
}
if (mainCamera.gameObject.GetComponent<UnityARCameraManager>() == null)
{
UnityARCameraManager unityARCameraManager = mainCamera.gameObject.AddComponent<UnityARCameraManager>();
unityARCameraManager.m_camera = mainCamera;
}
if (mainDirectionalLight.gameObject.GetComponent<UnityARAmbient>() == null)
{
mainDirectionalLight.gameObject.AddComponent<UnityARAmbient>();
}
UnityARSessionNativeInterface.ARFrameUpdatedEvent += ARFrameUpdated;
}
private void Update()
{
if (anchorSet == false && Input.GetMouseButtonDown(0))
{
Vector3 screenPosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
ARPoint point = new ARPoint
{
x = screenPosition.x,
y = screenPosition.y
};
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeHorizontalPlane);
if (hitResults.Count > 0)
{
anchorSet = true;
ChildrenSetActive(true);
gameObject.transform.position = UnityARMatrixOps.GetPosition(hitResults[0].worldTransform);
gameObject.transform.rotation = UnityARMatrixOps.GetRotation(hitResults[0].worldTransform);
}
}
}
public void InvaidatePlane()
{
anchorSet = false;
ChildrenSetActive(false);
}
private void ARFrameUpdated(UnityARCamera camera)
{
Debug.Log(string.Format("Points: {0}", camera.pointCloudData.Length));
}
private void ChildrenSetActive(bool active)
{
foreach (Transform childTransform in gameObject.transform)
{
childTransform.gameObject.SetActive(active);
}
}
private void Reset()
{
#if UNITY_EDITOR
if (clearMaterial == null)
{
clearMaterial = (Material)AssetDatabase.LoadAssetAtPath("Assets/UnityARKitPlugin/Plugins/iOS/UnityARKit/Materials/YUVMaterial.mat", typeof(Material));
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment