触摸旋转移动

using UnityEngine;
using System.Collections;

public class TouchRotateTarget : MonoBehaviour {

public Transform target;//绑定参照物
public float distance = 2f;//缩放系数

//左右滑动移动速度
public float xSpeed = 250.0f;
public float ySpeed = 120.0f;

//缩放限制系数
public int yMinLimit = -20;
public int yMaxLimit = 80;

//摄像头位置
public float x = 0.0f;
public float y = 0.0f;

//记录上一次手机触摸位置判断用户是放大还是缩小
private Vector2 oldPosition1;
private Vector2 oldPosition2;

//不让用户触摸操作
public bool TouchBOOL = false;

// Use this for initialization
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;

if (rigidbody)
rigidbody.freezeRotation = true;

}

// Update is called once per frame
void Update()
{

if (TouchBOOL == true)
{
//判断触摸数量为单点触摸
if (Input.touchCount == 1)
{
//触摸类型为移动触摸
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{
//根据触摸点计算X与Y位置
x += Input.GetAxis("Mouse X") * xSpeed * 0.015f;
y -= Input.GetAxis("Mouse Y") * xSpeed * 0.015f;
}
}

//判断触摸数量为多点触摸
if (Input.touchCount > 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))
{
//放大系数超过3,不允许继续放大
if (distance > 3)
{
distance -= 0.4f;
}
}
else
{
//缩小系数小于18.5,不允许缩小
if (distance < 20)
{
distance += 0.4f;
}
}
//备份上一次触摸的位置,用于对比
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;
}
}

void LateUpdate()
{
//target为我们绑定的箱子变量,缩放旋转的参照物
if (target)
{

//重置摄像机的位置
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
Vector3 disVector = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * disVector + target.position;

transform.rotation = rotation;
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);
}
}

转载于:https://www.cnblogs.com/ZeroMurder/p/5702346.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值