1. 程式人生 > >Unity3D -- 觸控輸入(移動和滑鼠)

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; } }