Skip to content

Instantly share code, notes, and snippets.

@edwios
Last active April 14, 2020 05:52
Show Gist options
  • Save edwios/d0c8a004cdb5254b73940207f6eb4712 to your computer and use it in GitHub Desktop.
Save edwios/d0c8a004cdb5254b73940207f6eb4712 to your computer and use it in GitHub Desktop.
Example to how to place a game object in AR mobile
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
[RequireComponent(typeof(ARRaycastManager))]
public class ARObjectHitDetect : MonoBehaviour
{
private RaycastHit _Rhit;
private bool _Hit;
void Awake()
{
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
{
Ray ray = Camera.main.ScreenPointToRay(touch.position);
_Hit = false;
// See if we "touched" anything in the AR world within 16m
if (Physics.Raycast(ray, out _Rhit, 16.0f))
{
_Hit = true;
Debug.Log($"We hit {_Rhit.transform.name}");
if (_Rhit.rigidbody != null)
{
Debug.Log($"We hit a rigibody {_Rhit.rigidbody.name}");
}
}
}
}
}
void FixedUpdate()
{
if (_Hit)
{
Debug.Log("Proocess physics etc on the "touched" AR object");
Transform hitTransform = _Rhit.transform;
Rigidbody hitRigidbody = _Rhit.rigidbody.GetComponent<Rigidbody>();
Vector3 hitPosition = _Rhit.point;
// ...
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
[RequireComponent(typeof(ARRaycastManager))]
public class ARObjectPlacement : MonoBehaviour
{
private ARRaycastManager raycastManager;
void Awake()
{
raycastManager = GetComponent<ARRaycastManager>();
}
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
{
if (raycastManager != null)
{
if (raycastManager.Raycast(touch.position, hits, TrackableType.PlaneWithinPolygon))
{
Pose hitPose = hits[0].pose;
// Instantiate Game Object at hitPose.position
// Optional set rotation of instantiated Game Object
}|
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment