unity-game-engineaugmented-reality8thwall-xr

Click on active surface to place GameObject with 8th Wall XR?


With 8th Wall XR is it possible to click on a surface and make it the active surface and place a gameobject on the position of the click? Kinda like ARKit which only augments the gameobject after clicking on it.


Solution

  • Something like this should do the trick. You'll need a GameObject (i.e. a Plane) with an XRSurfaceController attached, and put it on a Layer called "Surface":

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class PlaceObject : MonoBehaviour {
    
      // Adjust this if the transform isn't at the bottom edge of the object
      public float heightAdjustment = 0.0f;
    
      // Prefab to instantiate.  If null, the script will instantiate a Cube
      public GameObject prefab;
    
      // Scale factor for instantiated GameObject
      public float objectScale = 1.0f;
    
      private GameObject myObj;
    
      void Update() {
        // Tap to place
        if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began ) {
    
          RaycastHit hit;
          Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
          // The "Surface" GameObject with an XRSurfaceController attached should be on layer "Surface"
          // If tap hits surface, place object on surface
          if(Physics.Raycast(ray, out hit, 100.0f, LayerMask.GetMask("Surface"))) {
            CreateObject(new Vector3(hit.point.x, hit.point.y + heightAdjustment, hit.point.z));
          } 
        }
      }
    
      void CreateObject(Vector3 v) {
        // If prefab is specified, Instantiate() it, otherwise, place a Cube
        if (prefab) {
          myObj = GameObject.Instantiate(prefab);
        } else {
          myObj = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }
        myObj.transform.position = v;
        myObj.transform.localScale = new Vector3(objectScale, objectScale, objectScale);
      }
    }