Skip to content

Instantly share code, notes, and snippets.

@korinVR
Last active December 7, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korinVR/621ff3935ca8d415ca1000d01b6d1d49 to your computer and use it in GitHub Desktop.
Save korinVR/621ff3935ca8d415ca1000d01b6d1d49 to your computer and use it in GitHub Desktop.
Minimum VR EventSystem components
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace FrameSynthesis.XR.UnityUI
{
public class VRInputModule : BaseInputModule
{
readonly List<RaycastResult> raycastResults = new List<RaycastResult>();
public override void Process()
{
var pointerEventData = new PointerEventData(EventSystem.current);
eventSystem.RaycastAll(pointerEventData, raycastResults);
foreach (var raycastResult in raycastResults)
{
ExecuteEvents.Execute(raycastResult.gameObject, new BaseEventData(eventSystem), ExecuteEvents.submitHandler);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Zenject;
namespace FrameSynthesis.XR.UnityUI
{
public class VRRayCaster : BaseRaycaster
{
[Inject] ICameraRig cameraRig;
const float MaxDistance = 0.1f;
Canvas canvas;
public override Camera eventCamera => canvas.worldCamera != null ? canvas.worldCamera : Camera.main;
protected override void Awake()
{
canvas = GetComponent<Canvas>();
}
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
var rightHandTransform = cameraRig.GetTransform(TrackingPoint.RightHand);
var ray = new Ray(rightHandTransform.position, rightHandTransform.forward);
var graphics = GraphicRegistry.GetGraphicsForCanvas(canvas).ToList();
foreach (var graphic in graphics)
{
if (!IsRectTransformHit(graphic.rectTransform, ray, MaxDistance))
continue;
resultAppendList.Add(new RaycastResult
{
gameObject = graphic.gameObject,
});
}
}
static bool IsRectTransformHit(RectTransform rectTransform, Ray ray, float maxDistance)
{
var corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
var plane = new Plane(corners[0], corners[1], corners[2]);
return plane.Raycast(ray, out var enter) && enter < maxDistance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment