Input system手游的控制

手游离不开触屏控制

新的inputsystem

实现过程

  1. 安装input system
  2. 在projectsetting中的player的othersettings中active input handing设置both
  3. 打开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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值