Unity3D -- 触控输入(移动和鼠标)

使用同样的方法让移动端和鼠标可以同时操作触控输入,代码如下:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    private Vector3 m_PositionBegan = Vector3.zero;

    private Vector3 m_PostionEnd = Vector3.zero;

    /// <summary>
    /// 输入控制结构体
    /// </summary>
    public struct InputPhase
    {
        public TouchPhase phase;
        public Vector3 position;
    }

    void LateUpdate()
    {
        InputPhase inputPhase = GetInputPhase();

        if (inputPhase.position != null) {
            switch (inputPhase.phase) {
            case TouchPhase.Began:
                TouchBegan(inputPhase.position);
                break;
            case TouchPhase.Ended:
                TouchEnd(inputPhase.position);
                break;
            case TouchPhase.Stationary:
                break;
            case TouchPhase.Moved:
                break;
            }
        }
    }

    private void TouchBegan(Vector3 pos)
    {
        m_PositionBegan = pos;
        Debug.Log ("TouchBegan:" + m_PositionBegan);
    }

    private void TouchEnd(Vector3 pos)
    {
        m_PostionEnd = pos;
        Debug.Log ("TouchEnd:" + m_PositionBegan);
    }

    /// <summary>
    /// 获取输入信息
    /// </summary>
    /// <returns>The input phase.</returns>
    private InputPhase GetInputPhase()
    {
        InputPhase inputPhase = new InputPhase ();
        #if UNITY_EDITOR
        if(Input.GetMouseButtonDown(0)){
            inputPhase.phase = TouchPhase.Began;
            inputPhase.position = Input.mousePosition;
        }else if(Input.GetMouseButtonUp(0)){
            inputPhase.phase = TouchPhase.Ended;
            inputPhase.position = Input.mousePosition;
        }else if(Input.GetMouseButton(0)){
            inputPhase.phase = TouchPhase.Moved;
            inputPhase.position = Input.mousePosition;
        }
        #elif UNITY_IOS || UNITY_ANDROID

        if (Input.touchCount > 0) {
        Touch touch = Input.touches [0];
        inputPhase.phase = touch.phase;
        inputPhase.position = touch.position;
        }
        #else
        Debug.Log("Unable to identify the game running environment");
        #endif
        return inputPhase;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值