手游离不开触屏控制
新的inputsystem
实现过程
- 安装input system
- 在projectsetting中的player的othersettings中active input handing设置both
- 打开window的analysis的input debugger。在options中设置为simulate touch input from mouse or pen。
增强触摸控制的相关知识
启用
touch和finger
touch.activeFingers[]
中只存储激活的finger,依次按下两根手指,第一根的索引是0,第二根的索引就是1。抬起地一根手指,第二根手指的索引会变成0;
touch.fingers[]
按下后都存储,抬起的手指会标记为不激活状态。第一根的索引是0,第二根的索引就是1。抬起地一根手指,存储的信息会变成不激活,第二根手指的索引仍是1;
touch的阶段
began
moved
stationary
ended
canceled
使用
手指的移动距离存储在touchpos中。
需要用以下函数进行映射
touchPos = mainCam.ScreenToWorldPoint(touchPos);
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
using TouchPhase = UnityEngine.InputSystem.TouchPhase;
public class PlayersControls : MonoBehaviour
{
private Camera mainCam;
private Vector3 offset;
private float maxLeft;
private float maxRight;
private float maxDown;
private float maxUp;
// Start is called before the first frame update
void Start()
{
mainCam = Camera.main;
StartCoroutine(SetBoundaries());
}
// Update is called once per frame
void Update()
{
if (Touch.fingers[0].isActive)
{
Touch myTouch = Touch.activeTouches[0];
Vector3 touchPos = myTouch.screenPosition;
touchPos = mainCam.ScreenToWorldPoint(touchPos);
if (Touch.activeTouches[0].phase == TouchPhase.Began)
{
offset = touchPos - transform.position;
}
if (Touch.activeTouches[0].phase == TouchPhase.Moved)
{
transform.position = new Vector3(touchPos.x - offset.x, touchPos.y - offset.y, 0);
}
if (Touch.activeTouches[0].phase == TouchPhase.Stationary)
{
transform.position = new Vector3(touchPos.x - offset.x, touchPos.y - offset.y, 0);
}
transform.position = new Vector3(Mathf.Clamp(transform.position.x, maxLeft, maxRight),
Mathf.Clamp(transform.position.y, maxDown, maxUp), 0);
}
}
private void OnEnable()
{
EnhancedTouchSupport.Enable();
}
private void OnDisable()
{
EnhancedTouchSupport.Disable();
}
private IEnumerator SetBoundaries()
{
yield return new WaitForSeconds(0.4f);
maxLeft = mainCam.ViewportToWorldPoint(new Vector2(0.15f, 0)).x;
maxRight = mainCam.ViewportToWorldPoint(new Vector2(0.85f, 0)).x;
maxDown = mainCam.ViewportToWorldPoint(new Vector2(0, 0.05f)).y;
maxUp = mainCam.ViewportToWorldPoint(new Vector2(0, 0.6f)).y;
}
}