unity使用input system实现相机屏幕手势丝滑拖拽
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
using TouchPhase = UnityEngine.InputSystem.TouchPhase;
public class FingerScale : MonoBehaviour
{
private Vector3 _offset;
[SerializeField] private Camera mainCamera;
private Vector2 _firstTouchPosition;
private Vector2 _firstTouchStartPosition;
private Vector3 _firstTouchStartPositionToWorld;
private Vector2 _secondTouchPosition;
private Vector2 _secondTouchStartPosition;
public void OnFirstTouch(InputAction.CallbackContext context)
{
Debug.Log("OnFirstTouch"+context.phase);
_firstTouchStartPosition = context.ReadValue<Vector2>();
_firstTouchStartPositionToWorld = mainCamera.ScreenToWorldPoint(_firstTouchStartPosition);
}
public void OnTap(InputAction.CallbackContext context)
{
if (context.performed)
{
Vector3 worldPosition = new Vector3(_firstTouchStartPositionToWorld.x,
_firstTouchStartPositionToWorld.y, -20f);
StartCoroutine(MoveSmooth(worldPosition));
}
}
public void OnFirstPosition(InputAction.CallbackContext context)
{
_firstTouchPosition = context.ReadValue<Vector2>();
Debug.Log("onFirstPosition"+context.phase);
}
public void OnFirstMove(InputAction.CallbackContext context)
{
if (context.performed)
{
_offset = mainCamera.ScreenToWorldPoint(_firstTouchPosition)-_firstTouchStartPositionToWorld;
Debug.Log("_offset"+_offset);
mainCamera.transform.position -= _offset;
}
}
IEnumerator MoveSmooth(Vector3 targetPosition)
{
Vector3 start = mainCamera.transform.position;
Vector3 speed = Vector3.zero;
while (Vector3.Distance(start, targetPosition) > 0.001f)
{
mainCamera.transform.position = Vector3.SmoothDamp(start, targetPosition, ref speed, 0.3f);
start = mainCamera.transform.position;
yield return new WaitForEndOfFrame();
}
mainCamera.transform.position = targetPosition;
}
}