52 lines
1.6 KiB
C#
52 lines
1.6 KiB
C#
using UnityEngine;
|
|
|
|
namespace GazeLab.InputSystem
|
|
{
|
|
public sealed class KeyboardAimInput : MonoBehaviour, IAimInputSource
|
|
{
|
|
[Range(250f, 1800f)] public float cursorSpeedPixelsPerSec = 820f;
|
|
private Vector2 virtualCursorPos;
|
|
private bool initialized;
|
|
|
|
public AimControlMode ControlMode => AimControlMode.Keyboard;
|
|
|
|
private void EnsureInitialized()
|
|
{
|
|
if (!initialized)
|
|
{
|
|
virtualCursorPos = new Vector2(Screen.width * 0.5f, Screen.height * 0.55f);
|
|
initialized = true;
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
EnsureInitialized();
|
|
float h = UnityEngine.Input.GetAxisRaw("Horizontal");
|
|
float v = UnityEngine.Input.GetAxisRaw("Vertical");
|
|
Vector2 delta = new Vector2(h, v);
|
|
if (delta.sqrMagnitude > 0.001f)
|
|
{
|
|
if (delta.sqrMagnitude > 1f) delta.Normalize();
|
|
virtualCursorPos += delta * (cursorSpeedPixelsPerSec * Time.unscaledDeltaTime);
|
|
virtualCursorPos.x = Mathf.Clamp(virtualCursorPos.x, 12f, Screen.width - 12f);
|
|
virtualCursorPos.y = Mathf.Clamp(virtualCursorPos.y, 12f, Screen.height - 12f);
|
|
}
|
|
}
|
|
|
|
public void SyncCursorTo(Vector2 screenPos)
|
|
{
|
|
virtualCursorPos = screenPos;
|
|
initialized = true;
|
|
}
|
|
|
|
public bool TryGetScreenPosition(out Vector2 screenPixelPosition)
|
|
{
|
|
EnsureInitialized();
|
|
screenPixelPosition = virtualCursorPos;
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|