Input System Package + Raycasting (Unity)
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 anInput Action
asset. - Define an action for
Move
with action typeButton
and interactionPress
. - Add a
Player Input
component to the Game Object, and set its behavior toInvoke Unity Events
. - Bind the events to
OnMoveAction
andOnPointerPosition
Raycast
- If
isMoving
use thevalue
coming from thePointerPosition
action, and use it as aScreen 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}