在Unity中通过触摸屏幕实现模型的旋转和缩放

您所在的位置:网站首页 单机飞行游戏通过触摸屏幕来转向 在Unity中通过触摸屏幕实现模型的旋转和缩放

在Unity中通过触摸屏幕实现模型的旋转和缩放

2023-12-25 04:26| 来源: 网络整理| 查看: 265

// /**// *        ┏┓   ┏┓+ +// *       ┏┛┻━━━┛┻┓ + +// *       ┃       ┃  // *       ┃   ━   ┃ ++ + + +// *       ████━████ ┃+// *       ┃       ┃ +// *       ┃   ┻   ┃// *       ┃       ┃ + +// *       ┗━┓   ┏━┛// *         ┃   ┃           // *         ┃   ┃ + + + +// *         ┃   ┃    Code is far away from bug with the animal protecting       // *         ┃   ┃ +     神兽保佑,代码无bug  // *         ┃   ┃// *         ┃   ┃  +         // *         ┃    ┗━━━┓ + +// *         ┃        ┣┓// *         ┃        ┏┛// *         ┗┓┓┏━┳┓┏┛ + + + +// *          ┃┫┫ ┃┫┫// *          ┗┻┛ ┗┻┛+ + + +// *// *// * ━━━━━━感觉萌萌哒━━━━━━// * // * 说明:// * 此脚本用于手势控制物体的旋转和缩放// * 文件名:UserInputHandler.cs// * // *// */#pragma warning disable 0162

using UnityEngine;

/// /// 此脚本用于手势控制物体的旋转和缩放/// public class UserInputHandler : MonoBehaviour{

#if UNITY_IOS || UNITY_IPHONE public float horizontalSpeed = 0.2f; // 水平和垂直旋转的速度#endif#if UNITY_ANDROID

public float horizontalSpeed = 2.5f; // 水平和垂直旋转的速度#endif public float minScale = 0.6f; // 最小缩放比例 public float maxScale = 1.5f; // 最大缩放比例

private bool m_isOpenScaleGesture = true; /// /// 是否打开缩放手势 /// public bool IsOpenScaleGesture { get { return m_isOpenScaleGesture; } set { m_isOpenScaleGesture = value; } }

private bool m_isOpenRotationGesture = true; /// /// 是否打开 旋转手势 /// public bool IsOpenRotationGesture { get { return m_isOpenRotationGesture; } set { m_isOpenRotationGesture = value; } }

private Vector2 oldPos, newPos; // 此次点击和上次点击的位置 private Touch oldTouch1, oldTouch2; // 此次点击和上次点击的触摸对象

void Update() { //if (Stage.isTouchOnUI) //{ // return; //}

// 若是单点移动触控则进行旋转 if (IsOpenRotationGesture && Input.touchCount == 1) {

{ if (Input.GetTouch(0).phase == TouchPhase.Moved) { Vector2 deltaPosition = Input.GetTouch(0).deltaPosition; if (Mathf.Abs(deltaPosition.x) > 0.1f) { transform.Rotate(transform.up, -(deltaPosition.x * horizontalSpeed), Space.World); } } }

} else if (IsOpenScaleGesture && Input.touchCount == 2) { //多点触摸, 放大缩小 Touch newTouch1 = Input.GetTouch(0); Touch newTouch2 = Input.GetTouch(1);

//第2点刚开始接触屏幕, 只记录,不做处理 if (newTouch2.phase == TouchPhase.Began) { oldTouch2 = newTouch2; oldTouch1 = newTouch1; return; }

//计算老的两点距离和新的两点间距离,变大要放大模型,变小要缩放模型 float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position); float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position);

//两个距离之差,为正表示放大手势, 为负表示缩小手势 float offset = newDistance - oldDistance;

//放大因子, 一个像素按 0.01倍来算(100可调整) float scaleFactor = offset / 250f; Vector3 localScale = transform.localScale; Vector3 scale = new Vector3(localScale.x + scaleFactor, localScale.y + scaleFactor, localScale.z + scaleFactor);

// 限制缩放在一定的范围内 if (scale.x >= minScale && scale.x



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3