iLMS知識社群歷程檔登入
位置: 黃國哲 > Unity
1100608 上下左右放大縮小語法
by 黃國哲 2021-06-08 21:48:24, 回應(0), 人氣(450)

使用時搭配Event Trigger 的Down 和 Up 去開啟和關閉語法
再使用 Scroll Rect去限制移動範圍使其不會飛出邊界


Trigger腳本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class openclosescript : MonoBehaviour
{
    // Start is called before the first frame update

    public GameObject player;

    public void 抓取腳本開啟btn()
    { player.GetComponent<test>().enabled = true; }

    public void 抓取腳本關閉btn()
    { player.GetComponent<test>().enabled = false; }
}


移動腳本

using UnityEngine;
using System.Collections;
using System.IO;

public class test : MonoBehaviour
{
private Touch oldTouch1;  //上次觸控點1(手指1)
private Touch oldTouch2;  //上次觸控點2(手指2)
Vector2 m_screenPos = new Vector2();

void Start()
{ }

void Update()
{

//沒有觸控
if (Input.touchCount <= 0)
{return;}

//1個手指觸碰螢幕
if (Input.touchCount == 1)
{
//開始觸碰
if (Input.touches[0].phase == TouchPhase.Began)
{
//紀錄觸碰位置
m_screenPos = Input.touches[0].position;
//手指移動
}
else if (Input.touches[0].phase == TouchPhase.Moved)
{
//移動攝影機
transform.Translate(new Vector3(Input.touches[0].deltaPosition.x * Time.deltaTime*40, Input.touches[0].deltaPosition.y * Time.deltaTime*40, 0));
//transform.Translate(new Vector3(-Input.touches[0].deltaPosition.x * Time.deltaTime, -Input.touches[0].deltaPosition.y * Time.deltaTime, 0));
}
}
//多點觸控, 放大縮小
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 / 100f;
Vector3 localScale = transform.localScale;
Vector3 scale = new Vector3(localScale.x + scaleFactor,
localScale.y + scaleFactor,
localScale.z + scaleFactor);

//最小縮放到 1 倍,更改數字可以改變縮小比例,例如改成0.3為0.3倍
if (scale.x > 1f && scale.y > 1f && scale.z > 1f)
{
transform.localScale = scale;
}

//記住最新的觸控點,下次使用
oldTouch1 = newTouch1;
oldTouch2 = newTouch2;
}

}
回應