在Unity新输入系统中获取触摸位置的几个问题:
using UnityEngine;
using UnityEngine.InputSystem;
public class TouchInput : MonoBehaviour
{
private void Update()
{
Touchscreen touchscreen = Touchscreen.current;
if (touchscreen != null && touchscreen.touches.Count > 0)
{
Vector2 touchPosition = touchscreen.touches[0].screenPosition;
Debug.Log("Touch position: " + touchPosition);
}
}
}
以上代码首先获取当前的触摸屏幕对象,然后检查是否有触摸点存在,如果有,则获取第一个触摸点的屏幕位置。
touchscreen.touches
来获取所有触摸点的位置信息。例如,可以使用以下代码获取所有触摸点的屏幕位置:foreach (TouchState touch in touchscreen.touches)
{
Vector2 touchPosition = touch.screenPosition;
Debug.Log("Touch position: " + touchPosition);
}
通过遍历touchscreen.touches
,可以获取每个触摸点的屏幕位置。
using UnityEngine;
using UnityEngine.InputSystem;
public class TouchInput : MonoBehaviour
{
private void OnEnable()
{
Touchscreen touchscreen = Touchscreen.current;
if (touchscreen != null)
{
touchscreen.started += OnTouchStarted;
touchscreen.canceled += OnTouchCanceled;
touchscreen.performed += OnTouchPerformed;
}
}
private void OnDisable()
{
Touchscreen touchscreen = Touchscreen.current;
if (touchscreen != null)
{
touchscreen.started -= OnTouchStarted;
touchscreen.canceled -= OnTouchCanceled;
touchscreen.performed -= OnTouchPerformed;
}
}
private void OnTouchStarted(InputAction.CallbackContext context)
{
Vector2 touchPosition = context.ReadValue<Vector2>();
Debug.Log("Touch started at position: " + touchPosition);
}
private void OnTouchCanceled(InputAction.CallbackContext context)
{
Debug.Log("Touch canceled");
}
private void OnTouchPerformed(InputAction.CallbackContext context)
{
Vector2 touchPosition = context.ReadValue<Vector2>();
Debug.Log("Touch moved to position: " + touchPosition);
}
}
以上代码中,通过订阅touchscreen.started
、touchscreen.canceled
和touchscreen.performed
事件,可以分别处理触摸开始、触摸结束和触摸移动事件。在事件回调函数中,可以通过context.ReadValue<Vector2>()
获取触摸位置。
领取专属 10元无门槛券
手把手带您无忧上云