天天看點

Unity_AR_Vuforia_實作模型雙指放大縮小_旋轉功能

大家好,我是技術小白,自己寫部落格既可以當作筆記,又可以幫助他人,一舉兩得,何不美哉?

好了不廢話了,直接上代碼。

提醒一下和我一樣的入門小白,複制下面代碼粘貼到一個新的C#腳本裡時,

類名需要改成 和 外面檔案名相同,否則沒效果。

直接把下面腳本拖到 想要用雙指放大縮小的遊戲物體上即可。

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

//放大縮小功能 f
public class Scale : MonoBehaviour {

    Vector2 oldPos1;
    Vector2 oldPos2;

	// Use this for initialization
	void Start () {
		
	}

    // Update is called once per frame
    void Update() {
        if (Input.touchCount == 2) {
            if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved){
                Vector2 temPos1 = Input.GetTouch(0).position;
                Vector2 temPos2 = Input.GetTouch(1).position;

                if (isEnLarge(oldPos1, oldPos2, temPos1, temPos2))
                {
                    float oldScale = transform.localScale.x;
                    //放大的倍數 如果要修改 列如:oldScale * 1.025f 修改成 oldScale * 1.25f 根據自己需求修改
                    float newScale = oldScale * 1.025f;

                    transform.localScale = new Vector3(newScale, newScale, newScale);
                }else {
                    float oldScale = transform.localScale.x;
                    //縮小的倍數 如果要修改 列如:oldScale / 1.025f 修改成 oldScale / 1.25f 根據自己需求修改
                    float newScale = oldScale / 1.025f;

                    transform.localScale = new Vector3(newScale, newScale, newScale);
                }

                oldPos1 = temPos1;
                oldPos2 = temPos2;

            }
        }
	}

    bool isEnLarge(Vector2 oP1,Vector2 oP2,Vector2 nP1,Vector2 nP2) {

        float length1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
        float length2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));

        if (length1 < length2)
        {
            return true;
        }
        else {
            return false;
        }
        
    }
}
           

2.旋轉功能

提醒一下和我一樣的入門小白,複制下面代碼粘貼到一個新的C#腳本裡時,

類名需要改成 和 外面檔案名相同,否則沒效果。

直接把下面腳本拖到 想要用手指旋轉的遊戲物體上即可。

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

public class Rotate : MonoBehaviour {

    //上一個手指的位置
    //Vector3 PrevlousPosition;
    //手指的偏移值
    //Vector3 Offset;

    //速度
    float xSpeed = 150f;
    
	// Use this for initialization
	void Start () {
	    
	}
	
	// Update is called once per frame
	void Update () {

        //如果觸摸了螢幕
        if (Input.GetMouseButton(0)) {
            //判斷是幾個手指觸摸
            if (Input.touchCount == 1) {
                //第一個觸摸到手指頭 phase狀态 Moved滑動
                if (Input.GetTouch(0).phase == TouchPhase.Moved) {
                //根據你旋轉的 模型物體 是要圍繞哪一個軸旋轉 Vector3.up是圍繞Y旋轉
                    transform.Rotate(Vector3.up*Input.GetAxis("Mouse X") * xSpeed * Time.deltaTime);
                }
            }
        }
    }
}
           

補充一點(重要)

如果發現模型 點選沒有效果

可能是模型 沒有加碰撞體 Collider

繼續閱讀