一:滑动屏幕在固定轴上移动物体
using UnityEngine;
public class Test : MonoBehaviour
{
public float speed; //速度
//判断手势
private void JudgeGesture()
{
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
Vector2 touchDeltaPosition = touch.deltaPosition;
transform.Translate(touchDeltaPosition.x * speed, 0, 0);
}
}
}
}
二:点击屏幕
using UnityEngine;
public class Test : MonoBehaviour
{
//判断手势
private void JudgeGesture()
{
//单击
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
//TODO
}
}
//双击
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began && touch.tapCount == 2)
{
//TODO
}
}
}
}
三:长按屏幕
using UnityEngine;
public class Test : MonoBehaviour
{
private bool newTouch; //是否为新的触摸
private float touchTime; //触摸的时间
public float timeval;//时间间隔
//判断手势
private void JudgeGesture()
{
//长按
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
newTouch = true;
touchTime = Time.time;
}
else if (touch.phase == TouchPhase.Stationary)
{
if (newTouch && Time.time - touchTime > timeval)
{
//TODO
newTouch = false;
}
}
else
{
newTouch = false;
}
}
}
}
四:旋转物体
using UnityEngine;
public class Test : MonoBehaviour
{
public float speed; //速度
private void Update()
{
JudgeGesture();
}
//判断手势
private void JudgeGesture()
{
//旋转
if (Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
transform.Rotate(Vector3.up * Time.deltaTime * speed * -Input.GetAxis("Mouse X"));
}
}
}
}
五:缩放物体
using UnityEngine;
public class Test : MonoBehaviour
{
private Vector3 oldPos1; //手指1的旧位置
private Vector3 oldPos2; //手指2的旧位置
public float deltaValue; //缩放的增量值
public float maxScale; //最大的缩放值
public float minScale; //最小的缩放值
//判断手势
private void JudgeGesture()
{
//缩放
if (Input.touchCount == 2)
{
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
if (touch0.phase == TouchPhase.Moved || touch1.phase == TouchPhase.Moved)
{
Vector2 newPos1 = touch0.position;
Vector2 newPos2 = touch1.position;
if (Mathf.Abs(Vector3.Distance(newPos1, newPos2)) > Mathf.Abs(Vector3.Distance(oldPos1, oldPos2)))
{
if (transform.localScale.x > maxScale)
{
return;
}
float oldScale = transform.localScale.x;
float newScale = oldScale * deltaValue;
transform.localScale = new Vector3(newScale, newScale, newScale);
}
else if (Mathf.Abs(Vector3.Distance(newPos1, newPos2)) <
Mathf.Abs(Vector3.Distance(oldPos1, oldPos2)))
{
if (transform.localScale.x < minScale)
{
return;
}
float oldScale = transform.localScale.x;
float newScale = oldScale / deltaValue;
transform.localScale = new Vector3(newScale, newScale, newScale);
}
oldPos1 = newPos1;
oldPos2 = newPos2;
}
}
}
}