01.新建场景,然后随便找个模型丢进场景里,对光和相机进行调整。(我用的是自建的康师傅……贴图是从网上找的……已包含在TTT工具包的Models下了,需要的话自取) 02.从TTT插件中,将ObjectRotateAndScale.cs添加至模型上,为模型添加碰撞器,用于射线检测。 03.代码内容如下,tag那里和模型的标签记得根据自己的需求改! /// <summary> /// Copyright (c) 2021 MirzkisD1Ex0 All rights reserved. /// Code Version 1.0 /// </summary>
using System.Collections; using System.Collections.Generic; using UnityEngine;
namespace ToneTuneToolkit.Mobile { public class ObjectRotateAndScale : MonoBehaviour { private Vector2 oldPosA; private Vector2 oldPosB;
private void Update() { if (Input.GetMouseButton(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.collider.tag == "Player") // 如果射线不在Tag为Player的物体上则跳过后续的步骤 { if (Input.touchCount == 1) { ObjectRotate(); } if (Input.touchCount == 2) { ObjectScale(); } } } } }
/// <summary> /// 单指操作 /// 旋转 /// </summary> private void ObjectRotate() { if (Input.GetTouch(0).phase == TouchPhase.Moved) { float offsetX = Input.GetAxis("Mouse X"); float offsetY = Input.GetAxis("Mouse Y"); transform.Rotate(new Vector3(offsetY, -offsetX, 0) * 10f, Space.World); } return; }
/// <summary> /// 双指操作 /// 缩放 /// </summary> private void ObjectScale() { if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) { Vector2 newPosA = Input.GetTouch(0).position; Vector2 newPosB = Input.GetTouch(1).position; float oldScale; float newScale; oldScale = transform.localScale.x; if (IsEnlarge(oldPosA, oldPosB, newPosA, newPosB)) { newScale = oldScale * 1.02f; } else { newScale = oldScale / 1.02f; } transform.localScale = new Vector3(newScale, newScale, newScale); oldPosA = newPosA; oldPosB = newPosB; } }
/// <summary> /// 双指触点判断 /// 远了就是放大 /// </summary> /// <param name="oldPositionA"></param> /// <param name="oldPositionB"></param> /// <param name="newPositionA"></param> /// <param name="newPositionB"></param> /// <returns></returns> private bool IsEnlarge(Vector2 oldPositionA, Vector2 oldPositionB, Vector2 newPositionA, Vector2 newPositionB) { float oldDistance = Vector2.Distance(oldPositionA, oldPositionB); float newDistance = Vector2.Distance(newPositionA, newPositionB); if (oldDistance < newDistance) { return true; } return false; } } } 04.打包在安卓平台上,安装完毕后就可以看到效果,单指旋转,双指缩放。 嗯……静态图片看不出效果。 #region Introduction
此工程位于Github,遵从GPLv3.0协议,请根据需求使用。Pull完记得点个Star!
文章仅作抛砖引玉之用,希望能够借此给予寻求思路的开发者们一些灵感。
此教程系列曾属于“Unity The Great”,但由于“Tone Tune Tookit”的诞生,开发组决定将两个系列进行合并。
如果内容中出现了语混序乱、错鳖字、缺少标点符号的情况还请见谅
互联网精神永存。
Hooray!!!
#endregion
#region Developer
[团队代言人博客]
// https://www.cnblogs.com/mirzkisd1ex0/
[开发者邮箱]
// dearisaacyang@outlook.com
[开发者微信]
// wxid_63t8w3035kvp22
[开发者企鹅]
// 2957047371
#endregion