Skip to content

Instantly share code, notes, and snippets.

@dimmduh
Last active June 17, 2019 15:27
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 dimmduh/5c20b1dfdb0e723c3384bacb2431cb0a to your computer and use it in GitHub Desktop.
Save dimmduh/5c20b1dfdb0e723c3384bacb2431cb0a to your computer and use it in GitHub Desktop.
Test virutal cursor for unity (2019.1)
using UnityEngine;
using UnityEngine.EventSystems;
public class MyStandaloneInputModule : StandaloneInputModule
{
public RectTransform m_VirtualCursor;
private Vector2 m_LastMousePosition;
private Vector2 m_MousePosition;
public override void UpdateModule()
{
m_LastMousePosition = m_MousePosition;
m_MousePosition = m_VirtualCursor.anchoredPosition;
}
public override bool ShouldActivateModule()
{
var result = base.ShouldActivateModule();
if (result)
return true;
return (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
}
public override void ActivateModule()
{
base.ActivateModule();
m_MousePosition = m_VirtualCursor.anchoredPosition;
m_LastMousePosition = m_VirtualCursor.anchoredPosition;
}
private readonly MouseState m_MouseState = new MouseState();
private PointerEventData leftData;
protected override MouseState GetMousePointerEventData(int id)
{
// Populate the left button...
var created = GetPointerData(kMouseLeftId, out leftData, true);
leftData.Reset();
if (created)
leftData.position = m_VirtualCursor.anchoredPosition;
var pos = m_VirtualCursor.anchoredPosition;
leftData.delta = pos - leftData.position;
leftData.position = pos;
leftData.scrollDelta = Input.mouseScrollDelta;
leftData.button = PointerEventData.InputButton.Left;
eventSystem.RaycastAll(leftData, m_RaycastResultCache);
var raycast = FindFirstRaycast(m_RaycastResultCache);
leftData.pointerCurrentRaycast = raycast;
m_RaycastResultCache.Clear();
// copy the apropriate data into right and middle slots
PointerEventData rightData;
GetPointerData(kMouseRightId, out rightData, true);
CopyFromTo(leftData, rightData);
rightData.button = PointerEventData.InputButton.Right;
PointerEventData middleData;
GetPointerData(kMouseMiddleId, out middleData, true);
CopyFromTo(leftData, middleData);
middleData.button = PointerEventData.InputButton.Middle;
m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);
return m_MouseState;
}
}
using UnityEngine;
public class VirtualCursor : MonoBehaviour
{
public Vector3 offset;
private void Update()
{
transform.position = Input.mousePosition + offset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment