Unity双指控制缩放

Unity双指控制缩放

缩放原理

我所使用的缩放逻辑原理与其他人的可能不太一样,但也不是什么非常复杂的算法,可以说就是摄像机的拉近拉远,通过这种方式实现图像上的放大缩小。

代码

protected readonly Transform m_zoom = null;
private float max = 3.7f;
private float min = 0;
protected static float current = 0;
private float last = -1;
public void Update()
{
    if (Input.touchCount == 2)
    {
        float dis = Vector2.Distance(Input.touches[0].position, Input.touches[1].position);//两指之间的距离
        if (-1 == last) last = dis;
        float result = dis - last;//与上一帧比较变化
        if (result + current < min)//区间限制:最小
            result = min - current;
        else if (result + current > max)//区间限制:最大
            result = max - current;
        result *= 0.1f;//系数
        m_zoom.position += m_zoom.forward.normalized * result;
        current += result;//累计当前
        last = dis;//记录为上一帧的值
    }
    else
    {
        last = -1;//不触发逻辑时
    }
}

属性与方法

  • m_zoom是摄像机的对象,或摄像机某层父节点的对象,通过对它与场景中物体之间的位置变换,达到图像上放大缩小的效果。
  • Input.touchCount用于检测当前触碰的数量。Input.touchCount == 2表示当前接收到2个触碰信息。
  • Input.touches[0]Input.touches[1]是获取触碰信息,其中的数字便是触碰信息的相关索引。
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Unity中,可以使用Touch类来检测多点触控事件。要实现双图片,可以使用两个触摸点的位置和距离来计算比例。以下是一个简单的示例代码: ```csharp using UnityEngine; public class PinchZoom : MonoBehaviour { public float zoomSpeed = 0.5f; public float minZoom = 0.5f; public float maxZoom = 2.0f; private Vector2 previousTouchPosition1; private Vector2 previousTouchPosition2; void Update() { if (Input.touchCount == 2) { // Get the two touch positions Touch touch1 = Input.GetTouch(0); Touch touch2 = Input.GetTouch(1); // Calculate the touch delta Vector2 touchDelta1 = touch1.position - previousTouchPosition1; Vector2 touchDelta2 = touch2.position - previousTouchPosition2; float touchDeltaMagnitude = (touchDelta1 + touchDelta2).magnitude; // Calculate the zoom amount float zoomAmount = touchDeltaMagnitude * zoomSpeed * Time.deltaTime; // Update the camera's orthographic size Camera.main.orthographicSize = Mathf.Clamp(Camera.main.orthographicSize - zoomAmount, minZoom, maxZoom); // Save the touch positions for the next frame previousTouchPosition1 = touch1.position; previousTouchPosition2 = touch2.position; } else { // Reset the touch positions previousTouchPosition1 = Vector2.zero; previousTouchPosition2 = Vector2.zero; } } } ``` 在这个示例中,我们使用Camera的orthographicSize属性来实现。通过计算两个触摸点的位置和距离,我们可以计算出量,并将其应用于相机的orthographicSize。我们还可以使用minZoom和maxZoom变量来限制范围,确保不会超出定的范围。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天富儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值