What's Life Studio왓츠라이프 스튜디오

· ARPage

ARFoundation Object Creation :: 지면을 인식하여 터치로 물체 생성하기

ARFoundation을 활용하여 지면인식 후 오브젝트 생성하기

스크립트 생성

ARPlaneTouchPlace이라는 이름의 스크립트를 생성해서 다음과 같이 작성합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;

public class ARPlaneTouchPlace : MonoBehaviour
{
    public GameObject obj;
    
    ARRaycastManager arRaycastManager;
    static List<ARRaycastHit> hits = new List<ARRaycastHit>();

    private Vector2 touchPos;
    bool isSpawned;
    private GameObject spawnedObj;

    // Start is called before the first frame update
    void Start()
    {
        arRaycastManager = GetComponent<ARRaycastManager>();
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.touchCount > 0)
        {
            touchPos = Input.GetTouch(0).position;
            if(arRaycastManager.Raycast(touchPos, hits, TrackableType.PlaneWithinPolygon))
            {
                var hitPos = hits[0].pose;

                if (!isSpawned)
                {
                    spawnedObj = Instantiate(obj, hitPos.position, hitPos.rotation);
                    isSpawned = true;
                }
                else
                {
                    spawnedObj.transform.position = hitPos.position;
                }
                
            }
        }
    }
}