I’m using the new input system, and I have an action that I want to be able to perform from either the mouse & keyboard, or via a gamepad, and I figured I could accomplish this by using a custom InputProcessor.
My idea: I want a vector that denotes the direction the player is holding the right stick, and I want an equivalent of that with the mouse & keyboard, being the direction from the player (in screen coords) the the mouse position.
Is there any way to do this? I figure I need some kind of state stored within the processor that knows the player’s position on screen.
I figured out a way to do this, but it feels a tiny bit hacky. I’m holding on to references that are pulled on creation.
GameObject Player = GameObject.Find("Player");
Camera PlayerCam = Camera.main;
#region Register in editor
#if UNITY_EDITOR
static MousePositionToCamera()
{
Initialize();
}
#endif
[RuntimeInitializeOnLoadMethod]
static void Initialize()
{
InputSystem.RegisterProcessor<MousePositionToCamera>();
}
#endregion
/// <summary>
/// Returns the direction from the player's on-screen coordinates to where the
/// mouse's position is relative to the world
/// </summary>
/// <param name="value"></param>
/// <param name="control"></param>
/// <returns></returns>
public override Vector2 Process(Vector2 value, InputControl control)
{
var playerPosition = (Vector2)PlayerCam.WorldToViewportPoint(Player.transform.position);
var mousePosition = (Vector2)PlayerCam.ScreenToViewportPoint(value);
return (mousePosition - playerPosition).normalized;
}
I’m curious if there’s any better way to accomplish this!