using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; public class FurnitureSpawner : MonoBehaviour { [SerializeField] private ARRaycastManager arRaycastManager; [SerializeField] private GameObject furniturePrefab; private bool _canAddFurniture; private GameObject _furniturePreview; private Vector3 _detectedPosition = new(); private Quaternion _detectedRotation = Quaternion.identity; private ARTrackable _currentTrackable = null; private void Start() { InputHandler.OnTap += SpawnFurniture; _furniturePreview = Instantiate(furniturePrefab); SetCanAddFurniture(true); } private void SpawnFurniture() { if (!_canAddFurniture) return; var furniture = Instantiate(furniturePrefab); furniture.GetComponent().PlaceFurniture(_currentTrackable); furniture.transform.SetPositionAndRotation(_detectedPosition, _detectedRotation); } private void Update() { // Detect a position and rotation over the detected surface GetRaycastHitTransform(); } private void GetRaycastHitTransform() { var hits = new List(); var middleScreen = new Vector2(Screen.width / 2, Screen.height / 2); if (arRaycastManager.Raycast(middleScreen, hits, TrackableType.PlaneWithinPolygon)) { _detectedPosition = hits[0].pose.position; _detectedRotation = hits[0].pose.rotation; _furniturePreview.transform.SetPositionAndRotation(_detectedPosition, _detectedRotation); _currentTrackable = hits[0].trackable; } } private void OnDestroy() { InputHandler.OnTap -= SpawnFurniture; } private void SetCanAddFurniture(bool canAddFurniture) { _canAddFurniture = canAddFurniture; _furniturePreview.SetActive(canAddFurniture); } }