【Unity】ARKit床面認識した後でスマホTapした位置にUnity Chanをランダムに配置する

環境メモ
⭐️Mac OS Mojave バージョン10.14
⭐️Xcode version 10.0(10A255)
⭐️Unity 2018.2.14f1
⭐️iPhone7 IOS11.4.1

実際に動かした動画はこちら↓↓
https://twitter.com/nonnonkapibara/status/1061432598822453248

<img width="375" alt="IMG_0104.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/50367d9e-9216-11e4-1482-ec506fa20ae5.png">
<img width="375" alt="IMG_0105.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/d0821de8-c890-3d26-d807-587fad17e35b.png">

1.AssetsストアからUnity Chanのキャラクターをダウンロードする

「Optimize, SD Kohaku-Chanz!」を入力して、Downloadする

<img width="661" alt="001.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/b95ae945-7067-3975-e0a1-ab00b30558a6.png">

2.GameObjectを作り「UnityChanCollection」という名前にする
3.「Optimize　SDKohaku-Chanz」のAssetsから「Prefab」を選択して
UnityChanCollectionの中に、それぞれのPrefabをDrag&Dropして入れる。
4.「UnityChanCollection」を選択し、Inspectorを開く。
5.「Unity AR Hit TestExample」の「Hit Transform」で「HitCubeParent」を選択する
<img width="1213" alt="002.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/60a9f70b-5867-78af-5ade-749dc8ad81a1.png">

6.全てのキャラクターを選択した状態で、「Update Mode」を「Animate Physics」にする
<img width="1292" alt="003.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/3fa6f7c5-c9a7-5d51-f89d-63043692f08e.png">

Animator Componentリファレンス
https://docs.unity3d.com/ja/current/Manual/class-Animator.html
<img width="872" alt="004.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/a09f3e5a-b6a7-87ae-fc2c-292f217389b6.png">

7.Assetsを選択し、「UnityChanCollection」の中にあるキャラクターを全てAssets内にDrag&Dropして入れ込む
（Prefab化にする）
<img width="1001" alt="005.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/1cea7ad9-4522-8c10-ff16-b52d2a4eac38.png">

8.「UnityChanCollection」の中にあるキャラクターを全て削除する
（ソースコードの中で、キャラクターを生成する為）<img width="1306" alt="008.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/3f8f8fd1-e3c7-2e23-96a8-39942fc50ee3.png">

9.「Unity AR Hit TestExample」のソースコードを開く

```c#:UnityARHitTestExample
using System;
using System.Collections.Generic;

namespace UnityEngine.XR.iOS
{
	public class UnityARHitTestExample : MonoBehaviour
	{
		public Transform m_HitTransform;
		public float maxRayDistance = 30.0f;
		public LayerMask collisionLayer = 1 << 10;  //ARKitPlane layer
        // unity chanのGame Objectを宣言する
        public GameObject[] unityChanGameObject;
        // ランダム数
        private int unityChanNumber;

        // コメントアウト ここからStart
        /*
        bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
        {
            List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
            if (hitResults.Count > 0) {
                foreach (var hitResult in hitResults) {
                    Debug.Log ("Got hit!");
                    m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
                    m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
                    Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
                    return true;
                }
            }
            return false;
        }
        */
        // コメントアウト ここまで　End

        /*
         * Unity Chanを生成する
         */
        void CreateUnityChan(Vector3 position) {
            unityChanNumber = Random.Range(0, unityChanGameObject.Length);
            // Instantiateは「ランタイムにUnityChanを生成する」
            GameObject character = Instantiate(unityChanGameObject[unityChanNumber], position, Quaternion.identity);
            // LookAtは「対象の Transform を設定し、その方向へと向かせます」
            character.transform.LookAt(unityChanGameObject[unityChanNumber].transform);
            // transform.rotationは、回転
            character.transform.rotation = Quaternion.Euler(0.0f, character.transform.rotation.eulerAngles.y, character.transform.rotation.z);
        }
		
		// Update is called once per frame
		void Update () {
            // コメントアウト　Start
            /*
			#if UNITY_EDITOR   //we will only use this script on the editor side, though there is nothing that would prevent it from working on device
			if (Input.GetMouseButtonDown (0)) {
				Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
				RaycastHit hit;
				
				//we'll try to hit one of the plane collider gameobjects that were generated by the plugin
				//effectively similar to calling HitTest with ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent
				if (Physics.Raycast (ray, out hit, maxRayDistance, collisionLayer)) {
					//we're going to get the position from the contact point
					m_HitTransform.position = hit.point;
					Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));

					//and the rotation from the transform of the plane collider
					m_HitTransform.rotation = hit.transform.rotation;
				}
			}
			#else
            */
            //コメントアウト End

			if (Input.touchCount > 0 && m_HitTransform != null)
			{
				var touch = Input.GetTouch(0);
				if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
				{
					var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
					ARPoint point = new ARPoint {
						x = screenPosition.x,
						y = screenPosition.y
					};

                    List<ARHitTestResult> hitTestResultList = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeFeaturePoint);
                    if (hitTestResultList.Count > 0) {
                        foreach(var entity in hitTestResultList) {
                            Vector3 position = UnityARMatrixOps.GetPosition(entity.worldTransform);
                            // Unity Chanを生成する
                            CreateUnityChan(new Vector3(position.x, position.y, position.z));
                        }
                    }

                    // コメントアウト　Start
                    /*
                    // prioritize reults types
                    ARHitTestResultType[] resultTypes = {
						//ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingGeometry,
                        ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent, 
                        // if you want to use infinite planes use this:
                        //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
                        //ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane, 
						//ARHitTestResultType.ARHitTestResultTypeEstimatedVerticalPlane, 
						//ARHitTestResultType.ARHitTestResultTypeFeaturePoint
                    }; 
					
                    foreach (ARHitTestResultType resultType in resultTypes)
                    {
                        if (HitTestWithResultType (point, resultType))
                        {
                            return;
                        }
                    }
                    */
                    // コメントアウト End
                }
			}
            // コメントアウト
            //#endif
        }
    }
}
```

10.「UnityChanCollection」を選択し、「Unity Chan Game Object」を０から７に変更する
（キャラクターが７つあるので。）
<img width="1306" alt="008.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/4811676d-8b2b-3154-b786-c6eac10d7eb1.png">

①UTC_Default
<img width="106" alt="スクリーンショット 2018-11-11 10.59.44.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/dea8606d-b5e2-dac6-a485-18d4248416ad.png">

②UTC_SchoolUniform_summer
<img width="77" alt="スクリーンショット 2018-11-11 11.00.13.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/797613db-3ff3-2dc3-95ca-eca5131b06db.png">

③UTC_SchoolUniform_Winter
<img width="85" alt="スクリーンショット 2018-11-11 11.00.42.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/8df544eb-5176-b970-3feb-10849a7c9e34.png">

④Misaki_SchoolUniform_Winter
<img width="75" alt="スクリーンショット 2018-11-11 11.01.38.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/2d2277ae-ed13-88ac-0aa7-c10ced365797.png">

⑤Misaki_SchoolUniform_summer
<img width="79" alt="スクリーンショット 2018-11-11 11.01.09.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/135e15e9-d022-f7c4-62b6-bb5400a00bcc.png">

⑥Yuko_SchoolUniform_summer
<img width="70" alt="スクリーンショット 2018-11-11 11.02.17.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/1c25f4e2-7f65-7b8a-36eb-15652790a560.png">

⑦Yuko_SchoolUniform_Winter
<img width="75" alt="スクリーンショット 2018-11-11 11.02.24.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/c040b127-99f2-b02f-d7e7-042e1fda82fa.png">

11.Assetsの中の７つのキャラクターを順番に、Untiy Chan Objectの　ElementにDrag＆Dropしていく。
<img width="1291" alt="009.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/91501a59-aa82-6702-66a5-90c6a09d8a7f.png">
<img width="1294" alt="010.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/0522f3da-c7b2-0f9a-2b3f-620bab79b71a.png">

完成！！


12.最終的に、７つのキャラクターの「Rotaiton」を９０にし、サイズも0.1にして小さくしました。
<img width="702" alt="011.png" src="https://qiita-image-store.s3.amazonaws.com/0/93155/ee36c1be-a160-023b-0e24-0b7506c7b4d0.png">