Input System Package + Raycasting (Unity)

z4gon
z4gon

Using Input Action events to Raycast points from Screen Space onto a Plane.

References

Table of Content


Input Actions

  • Install the Input System Package and create an Input Action asset.
  • Define an action for Move with action type Button and interaction Press.
  • Add a Player Input component to the Game Object, and set its behavior to Invoke Unity Events.
  • Bind the events to OnMoveAction and OnPointerPosition

Picture Picture Picture


Raycast

  • If isMoving use the value coming from the PointerPosition action, and use it as a Screen Position vector.
  • Use Camera.ScreenPointToRay to obtain a ray and raycast it onto the plane.
  • Move the player to the hit transform position.
1private Camera mainCamera; 2private LayerMask raycastLayerMask; 3private float raycastMaxDistance = 40; 4private bool isMoving = false; 5 6public void OnMoveAction(InputAction.CallbackContext context) 7{ 8 isMoving = context.performed; 9} 10 11public void OnPointerPosition(InputAction.CallbackContext context) 12{ 13 if (!isMoving) 14 { 15 return; 16 } 17 18 var point = context.ReadValue<Vector2>(); 19 var ray = mainCamera.ScreenPointToRay(point); 20 RaycastHit hit; 21 22 if ( 23 Physics.Raycast( 24 ray, 25 out hit, 26 raycastMaxDistance, 27 raycastLayerMask, 28 QueryTriggerInteraction.Collide 29 ) 30 ) 31 { 32 transform.position = hit.point; 33 } 34}

Picture