Created
November 8, 2021 14:35
-
-
Save didacus/0297fa48d9583f016e4dffbe24a7267c to your computer and use it in GitHub Desktop.
SpawnableManager AR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.XR.ARFoundation; | |
public class SpawnableManager : MonoBehaviour | |
{ | |
[SerializeField] | |
ARRaycastManager m_RaycastManager; | |
List<ARRaycastHit> m_Hits = new List<ARRaycastHit>(); | |
[SerializeField] | |
GameObject spawnablePrefab; | |
Camera arCam; | |
GameObject spawnedObject; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
spawnedObject = null; | |
arCam = GameObject.Find("AR Camera").GetComponent<Camera>(); | |
} | |
//Update is called once per frame | |
void Update() | |
{ | |
if (Input.touchCount == 0) | |
return; | |
RaycastHit hit; | |
Ray ray = arCam.ScreenPointToRay(Input.GetTouch(0).position); | |
if(m_RaycastManager.Raycast(Input.GetTouch(0).position, m_Hits)) | |
{ | |
if(Input.GetTouch(0).phase == TouchPhase.Began && spawnedObject == null) | |
{ | |
if (Physics.Raycast(ray, out hit)) | |
{ | |
if (hit.collider.gameObject.tag == "Spawnable") | |
{ | |
spawnedObject = hit.collider.gameObject; | |
} | |
else | |
{ | |
SpawnPrefab(m_Hits[0].pose.position); | |
} | |
} | |
} | |
else if(Input.GetTouch(0).phase == TouchPhase.Moved && spawnedObject != null) | |
{ | |
spawnedObject.transform.position = m_Hits[0].pose.position; | |
} | |
if(Input.GetTouch(0).phase == TouchPhase.Ended) | |
{ | |
spawnedObject = null; | |
} | |
} | |
} | |
private void SpawnPrefab(Vector3 spawnPosition) | |
{ | |
spawnedObject = Instantiate(spawnablePrefab, spawnPosition, Quaternion.identity); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment