Unity 觸屏操作
當將Unity游戲運行到IOS或Android設(shè)備上時,桌面系統(tǒng)的鼠標左鍵可以自動變?yōu)槭謾C屏幕上的觸屏操作,但如多點觸屏等操作卻是無法利用鼠標操作進行的。Unity的Input類中不僅包含桌面系統(tǒng)的各種輸入功能,也包含了針對移動設(shè)備觸屏操作的各種功能,下面介紹一下Input類在觸碰操作上的使用。
首先介紹一下Input.touches結(jié)構(gòu),這是一個觸摸數(shù)組,每個記錄代表著手指在屏幕上的觸碰狀態(tài)。每個手指觸控都是通過Input.touches來描述的:
fingerId:觸摸的唯一索引
position:觸摸屏幕的位置
deltatime:從最后狀態(tài)到目前狀態(tài)所經(jīng)過的時間
tapCount:點擊數(shù)。Andorid設(shè)備不對點擊計數(shù),這個方法總是返回1
deltaPosition:自最后一幀所改變的屏幕位置
-
phase:觸摸狀態(tài),也即屏幕操作狀態(tài)
- Began:手指剛剛觸摸屏幕
- Move:手指剛剛觸摸屏幕
- Stationary:手指觸摸屏幕,但自最后一陣沒有移動
- Ended:手指離開屏幕
- Canceled:系統(tǒng)取消觸控跟蹤,原因如把設(shè)備放在臉上或同時超過5個觸摸點
using UnityEngine;
public class MobileTouch : MonoBehaviour
{
private int isforward;//標記攝像機的移動方向
private Vector2 oposition1 = new Vector2();
private Vector2 oposition2 = new Vector2();
Vector2 m_screenPos = new Vector2();
private void Update()
{
if (Input.touchCount <= 0) return;
if (Input.touchCount == 1) //單點觸碰移動攝像機
{
if (Input.touches[0].phase == TouchPhase.Began)
m_screenPos = Input.touches[0].position; //記錄手指剛觸碰的位置
if (Input.touches[0].phase == TouchPhase.Moved) //手指在屏幕上移動,移動攝像機
{
transform.Translate(new Vector3(Input.touches[0].deltaPosition.x * Time.deltaTime, Input.touches[0].deltaPosition.y * Time.deltaTime, 0));
}
}
else if (Input.touchCount > 1)//多點觸碰
{
//記錄兩個手指的位置
Vector2 nposition1 = new Vector2();
Vector2 nposition2 = new Vector2();
//記錄手指的每幀移動距離
Vector2 deltaDis1 = new Vector2();
Vector2 deltaDis2 = new Vector2();
for (int i = 0; i < 2; i++)
{
Touch touch = Input.touches[i];
if (touch.phase == TouchPhase.Ended)
break;
if (touch.phase == TouchPhase.Moved) //手指在移動
{
if (i == 0)
{
nposition1 = touch.position;
deltaDis1 = touch.deltaPosition;
}
else
{
nposition2 = touch.position;
deltaDis2 = touch.deltaPosition;
// 判斷手勢伸縮從而進行攝像機前后移動參數(shù)縮放效果
if (isEnlarge(oposition1, oposition2, nposition1, nposition2))
isforward = 1;
else
isforward = -1;
}
//記錄舊的觸摸位置
oposition1 = nposition1;
oposition2 = nposition2;
}
//移動攝像機
Camera.main.transform.Translate(isforward * Vector3.forward * Time.deltaTime * (Mathf.Abs(deltaDis2.x + deltaDis1.x) + Mathf.Abs(deltaDis1.y + deltaDis2.y)));
}
}
}
//用于判斷是否放大
private bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2)
{
//函數(shù)傳入上一次觸摸兩點的位置與本次觸摸兩點的位置計算出用戶的手勢
float leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
float leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));
return leng1 < leng2;
}
}
將這個腳本綁定在主攝像機上,發(fā)現(xiàn)單觸摸操作可上下左右移動攝像機,雙觸摸操作可以縮放。
導出Android 在手機上運行,可以發(fā)現(xiàn)觸摸起了效果。