首先介绍一下Input.touches结构,这是一个触摸数组,每个记录代表着手指在屏幕上的触碰状态。每个手指触控都是通过Input.touches来描述的:
|
fingerId |
触摸的唯一索引 |
|
position |
触摸屏幕的位置 |
|
deltatime |
从最后状态到目前状态所经过的时间 |
|
tapCount |
点击数。Andorid设备不对点击计数,这个方法总是返回1 |
|
deltaPosition |
自最后一帧所改变的屏幕位置 |
|
phase |
相位,也即屏幕操作状态 |
其中phase(状态)有以下这几种:
|
Began |
手指刚刚触摸屏幕 |
|
Moved |
手指在屏幕上移动 |
|
Stationary |
手指触摸屏幕,但自最后一阵没有移动 |
|
Ended |
手指离开屏幕 |
|
Canceled |
系统取消触控跟踪,原因如把设备放在脸上或同时超过5个触摸点
|
在Unity 游戏运行在手机上时鼠标左键的操作可以用触摸屏幕来代替,但是无法代替多点的触控。(也就是说在调用getaxis和getmousebutton等方法时手机上进行触摸屏幕也可以响应)
下面是通过在手机上进行操作来实现旋转和放大缩小的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float rotateSpeed;
public Vector2 nTouchPos1;
public Vector2 nTouchPos2;
public Vector2 oTouchPos1;
public Vector2 oTouchPos2;
// Update is called once per frame
void Update()
{
//旋转
if (Input.GetMouseButton(0))
{
if (Input.touchCount == 1)
{
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{
Debug.Log("开始旋转");
float moveX = Input.GetTouch(0).deltaPosition.x;
Debug.Log("滑动的距离" + moveX);
transform.Rotate(Vector3.up * -rotateSpeed * moveX * Time.deltaTime);
}
}
}
ZoomInOut();
if (this.transform.position.y > 0)
{
return;
}
this.transform.Translate(new Vector3(0, 0.5f, 0) * Time.deltaTime);
}
bool IsEnLarge(Vector2 nPos1,Vector2 nPos2,Vector2 oPos1,Vector2 oPos2)
{
float nDis = Vector2.Distance(nPos1, nPos2);
float oDis = Vector2.Distance(oPos1, oPos2);
if(nDis<oDis)
{
return false;
}
else
{
return true;
}
}
void ZoomInOut()
{
if(Input.touchCount==2)
{
if(Input.GetTouch(0).phase==TouchPhase.Moved||Input.GetTouch(1).phase==TouchPhase.Moved)
{
nTouchPos1 = Input.GetTouch(0).position;
nTouchPos2 = Input.GetTouch(1).position;
if(IsEnLarge(nTouchPos1,nTouchPos2,oTouchPos1,oTouchPos2))
{
Vector3 nScale = transform.localScale*1.01f;
transform.localScale = new Vector3(nScale.x, nScale.y, nScale.z);
}
else
{
Vector3 nScale = transform.localScale *0.99f;
transform.localScale = new Vector3(nScale.x, nScale.y, nScale.z);
}
oTouchPos1 = nTouchPos1;
oTouchPos2 = nTouchPos2;
}
}
}
}
原文:https://www.cnblogs.com/v5-otto/p/11628767.html