63 lines
1.6 KiB
C#
Raw Normal View History

using System;
2023-11-14 11:51:12 -05:00
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.XR.Interaction.Toolkit;
namespace Interactions
{
public class XRScroll : XRBaseInteractable
2023-11-14 11:51:12 -05:00
{
private bool isTracking;
2023-11-14 11:51:12 -05:00
[SerializeField] private Vector3 scrollAxis = Vector3.up;
[SerializeField] private float scrollScale = 1000;
public UnityEvent<float> scrollUpdated;
2023-11-14 11:51:12 -05:00
protected override void OnDisable()
{
base.OnDisable();
isTracking = false;
StopAllCoroutines();
}
2023-11-14 11:51:12 -05:00
public void OnSelected(SelectEnterEventArgs args)
{
StartCoroutine(TrackScrolling(args.interactorObject.transform));
2023-11-14 11:51:12 -05:00
}
private IEnumerator TrackScrolling(Transform mover)
2023-11-14 11:51:12 -05:00
{
if (isTracking) yield break;
isTracking = true;
2023-11-14 11:51:12 -05:00
Vector3 previousPos = mover.position;
while (isTracking)
2023-11-14 11:51:12 -05:00
{
yield return null;
Vector3 currentPos = mover.position;
//Calculate the difference in position only along one axis
2023-11-14 11:51:12 -05:00
Vector3 diff = (previousPos - currentPos);
diff = new Vector3(diff.x * scrollAxis.x, diff.y * scrollAxis.y, diff.z * scrollAxis.z);
float diffTotal = (diff.x + diff.y + diff.z) * scrollScale;
2023-11-14 11:51:12 -05:00
previousPos = currentPos;
scrollUpdated?.Invoke(diffTotal);
2023-11-14 11:51:12 -05:00
}
}
public void OnUnSelected(SelectExitEventArgs args)
{
isTracking = false;
2023-11-14 11:51:12 -05:00
}
}
}