点击触摸直接使用GetMouseButton(0)即可,下面我们通过这个思路实现双击和长按
其中下面的newTouch和touchTime是用来控制长按的是否以及时间,保证一个位置的长按只能触发一次长按的方法
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
#region 双击
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)//判断几个点击位置而且是最开始点击的屏幕,而不是滑动屏幕
{
if (Input.GetTouch(0).tapCount == 2)//tapcount是点击次数
{
Destroy(hit.collider.gameObject);
}
}
#endregion
#region 长按
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)//点击没有滑动的时候会触发Stationary
{
if (newTouch == true && Time.time - touchTime > 1f)
{
newTouch = false;
Destroy(hit.collider.gameObject);
}
}
else
{
newTouch = false;
}
}
#endregion
}
滑动屏幕比较简单,只需要修改phase的值即可,判断当前点击的位置处于什么阶段即可
if (Input.GetMouseButton(0))
{
if (Input.touchCount==1)
{
if (Input.GetTouch(0).phase==TouchPhase.Moved)//滑动状态
{
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * -xSpeed * Time.deltaTime,Space.World);
}
}
}
判断是否是双指操作放大缩小,通过手势缩放来控制人物模型的缩放
/// <summary>
/// 判断手势
/// </summary>
/// <param name="op1">开始的第一个点</param>
/// <param name="op2">开始的第二个点</param>
/// <param name="np1">结束的第一个点</param>
/// <param name="np2">结束的第二个点</param>
/// <returns></returns>
bool isEnlarge(Vector2 op1, Vector2 op2, Vector2 np1, Vector2 np2)
{
float startLength = Mathf.Sqrt((op1.x - op2.x) * (op1.x - op2.x)+ (op1.y - op2.y) * (op1.y - op2.y));
float endLength = Mathf.Sqrt((np1.x - np2.x) * (np1.x - np2.x) + (np1.y - np2.y) * (np1.y - np2.y));
if (startLength<endLength)
{
return true;
}
else
{
return false;
}
}
Vector2 oldPos1;
Vector2 oldPos2;
void Update () {
if (Input.touchCount==2)
{
if (Input.GetTouch(0).phase==TouchPhase.Moved||Input.GetTouch(1).phase==TouchPhase.Moved)
{
Vector2 temPosl = Input.GetTouch(0).position;
Vector2 temPos2 = Input.GetTouch(1).position;
if (isEnlarge(oldPos1,oldPos2,temPosl,temPos2))
{
float oldScale = transform.localScale.x;
float newScale= oldScale*1.025f;
transform.localScale = new Vector3(newScale, newScale, newScale);
}
else
{
float oldScale = transform.localScale.x;
float newScale = oldScale / 1.025f;
transform.localScale = new Vector3(newScale, newScale, newScale);
}
oldPos1 = temPosl;
oldPos2 = temPos2;
}
}
}