c# - Unity 多点触控(捏合)缩放对象
问题描述
我正在尝试使用多点触控(捏)来缩放对象。
它工作正常,但是当我放开 2 次触摸并尝试再次放大和缩小时,
对象一直试图回到其原始比例。
我使用了下面的代码。
if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Moved)
{
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
float pinchAmount = deltaMagnitudeDiff * 0.02f * Time.deltaTime;
objectImRotating.transform.localScale += new Vector3(pinchAmount, pinchAmount, pinchAmount);
}
解决方案
我不知道问题的原因,但我会这样做:而不是使用逐帧添加进行缩放,而是执行类似的操作
private Vector2 initialDistance;
private Vector3 initialScale;
private void Update()
{
if (Input.touchCount == 2)
{
var touchZero = Input.GetTouch(0);
var touchOne = Input.GetTouch(1);
// if one of the touches Ended or Canceled do nothing
if(touchZero.phase == TouchPhase.Ended || touchZero.phase == TouchPhase.Canceled
|| touchOne.phase == TouchPhase.Ended || touchOne.phase == TouchPhase.Canceled)
{
return;
}
// It is enough to check whether one of them began since we
// already excluded the Ended and Canceled phase in the line before
if(touchZero.phase == TouchPhase.Began || touchOne.phase == TouchPhase.Began)
{
// track the initial values
initialDistance = Vector2.Distance(touchZero.position, touchOne.position);
initialScale = objectImRotating.transform.localScale;
}
// else now is any other case where touchZero and/or touchOne are in one of the states
// of Stationary or Moved
else
{
// otherwise get the current distance
var currentDistance = Vector2.Distance(touchZero.position, touchOne.position);
// A little emergency brake ;)
if(Mathf.Approximately(initialDistance, 0)) return;
// get the scale factor of the current distance relative to the inital one
var factor = currentDistance / initialDistance;
// apply the scale
// instead of a continuous addition rather always base the
// calculation on the initial and current value only
objectImRotating.transform.localScale = initialScale * factor;
}
}
}
在智能手机上打字,但我希望这个想法很清楚
推荐阅读
- node.js - node_modules/@types/lodash/common/array.d.ts(37,24) 中的错误:错误 TS1005:';' 预期的
- javascript - Python Selenium Webdriver - Python 脚本中的 Javascript .click() 集成
- php - Laravel 会话闪存
- java - 错误:- 不能从静态上下文 PermissionToken.continuePermissionRequest() 引用非静态方法 continuePermissionRequest();
- python - 如何为 Jira REST API 安装 Python 包
- java - 接口 Workbook 和类 WorkbookFactory 返回错误“无法解析为类型”
- javascript - 如何更新 aurealia 中的 observable
- node.js - 如何将一些文件导入 webpack 的入口文件?
- google-apps-script - 挑战:将使用 GAS 制作的 RESPONSIVE Web App Form 放入 HTML 页面
- r - 除了 (1) naniar - , (2) BaylorEdpsych - , (3) MissMech - 包括“Littles mcar_test”的包之外,还有其他包吗?