【Unity】7.5 行動裝置輸入

來源:互聯網
上載者:User

標籤:

分類:Unity、C#、VS2015

建立日期:2016-04-21 一、簡介

在iOS和Android系統中,操作都是通過觸摸來完成的。Input類中對觸摸操作的方法或變數如所示:

通過GetTouch或者touches可以訪問移動沒備的觸摸資料,資料儲存在Touch的結構體中。是Touch的結構體變數:

二、基本用法樣本

1、樣本1(遍曆所有Touch並輸出Touch的資訊)

void OnGUI()

{

//遍曆所有Touch

foreach(Touch touch in Input.touches)

{

//輸出Touch資訊

GUILayout.Label(string.Format("手指:{0} 狀態:{1} 位置:{2}",touch.fingerId,touch.phase.ToString(),touch.position));

}

}

2、樣本2(Demo5_2_MobileExample.unity)

該例子示範如何列印當前觸控螢幕幕的手指數量。

下面是MobileExample.cs檔案中的代碼:

using UnityEngine;using System.Collections;public class MobileExample : MonoBehaviour{    //定義手指在觸控螢幕上的數量    public int fingerCount = 0;    void Update()    {        foreach (var touch in Input.touches)        {            if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)                fingerCount++;        }        if (fingerCount > 0)            print("使用者有 " + fingerCount + " 手指觸摸了螢幕");    }    void OnGUI()    {        //輸出手指在觸控螢幕上的數量至介面中        GUILayout.Label("手指數量:" + fingerCount);    }}

運行預覽效果:

3、樣本3(Demo5_3_MobileMoveExample.unity)

該例子示範如何根據手指在螢幕上的滑動來移動物體。

MobileMoveExample.cs檔案的代碼如下:

using UnityEngine;using System.Collections;public class MobileMoveExample : MonoBehaviour{    public float speed = 0.1f;    void Update()    {        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)        {            // 得到手指在這一幀的移動距離            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;            // 在XY平面上移動物體            transform.Translate(-touchDeltaPosition.x * speed, -touchDeltaPosition.y * speed, 0);        }    }}

運行預覽效果和樣本2的相同。

【Unity】7.5 行動裝置輸入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.