UNITY移动平台上的手势操作——旋转、缩放

UNITY移动平台上的⼿势操作——旋转、缩放
通过UNITY⾃带的Touch可以实现安卓和IOS两个平台都兼容。效果是通过单⼿指滑动摄像机绕着⽬标点旋转(看起来就像是物体在旋转)。通过双指操作拉近或者拉远摄像机实现放⼤缩⼩操作。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
ct扫描
public class CamRotation : MonoBehaviour {
public Transform target;
public float distance = 30.0f;
//上下左右滑动速度
float xSpeed = 250.0f;
float ySpeed = 120.0f;
//缩放限制系数(拉近拉远的距离)
float yMinLimit = -20;
float yMaxLimit = 80;
//摄像头的位置
float x = 0.0f;
float y = 0.0f;
//记录上⼀次⼿机触摸位置判断⽤户是在左放⼤还是缩⼩⼿势
private Vector2 oldPosition1;
private Vector2 oldPosition2;
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
}
void Update()
{
//判断触摸数量为单点触摸
if (uchCount == 1)
{
//触摸类型为移动触摸
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{给刘翔的一封信
//根据触摸点计算X与Y位置
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
胞嘧啶y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
}苟仲武
}
//判断触摸数量为多点触摸
if (uchCount > 1)
{
//前两只⼿指触摸类型都为移动触摸
if (Input.GetTouch(0).phase == TouchPhase.Moved||Input.GetTouch(1).phase == TouchPhase.Moved)
{
//计算出当前两点触摸点的位置
Vector2 tempPosition1 = Input.GetTouch(0).position;
Vector2 tempPosition2 = Input.GetTouch(1).position;
//函数返回真为放⼤,返回假为缩⼩
if (isEnlarge(oldPosition1, oldPosition2, tempPosition1, tempPosition2))
{
//放⼤系数超过15以后不允许继续放⼤
if (distance > 15)
{
{
中国防水网
distance -= 0.5f;
}
}
else
{
//缩⼩系数⼩于30后不允许继续缩⼩
if (distance < 30)
{
distance += 0.5f;
}
}
黑龙江畜牧兽医投稿/
/备份上⼀次触摸点的位置,⽤于对⽐
oldPosition1 = tempPosition1;
oldPosition2 = tempPosition2;
}
}
}
//函数返回真为放⼤,返回假为缩⼩
bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2 )
{
//函数传⼊上⼀次触摸两点的位置与本次触摸两点的位置计算出⽤户的⼿势
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));
if(leng1<leng2)
{
//放⼤⼿势
return true;
}else
{
//缩⼩⼿势
return false;
}
}
/
/Update⽅法⼀旦调⽤结束以后进⼊这⾥算出重置摄像机的位置
void  LateUpdate()
{
//target为我们绑定的箱⼦变量,缩放旋转的参照物
if (target)
{
//重置摄像机的位置
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
Vector3 position = rotation *new  Vector3(0.0f, 0.0f, -distance) + target.position;
transform.position = position;
}
}
static float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}

本文发布于:2024-09-22 06:48:17,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/124855.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:触摸   旋转   位置   拉近
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议